<?php
session_start();

header("Access-Control-Allow-Origin: https://enerliths.com");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Headers: Content-Type");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Content-Type: application/json");

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}
require "../config/db.php";



$user_id = $_SESSION["user_id"];

$uploadDir = "../uploads/kyc/";

if(!is_dir($uploadDir)){
 mkdir($uploadDir,0777,true);
}

function saveFile($file,$prefix){

 global $uploadDir;

 $name = $prefix."_".time()."_".basename($file["name"]);
 $path = $uploadDir.$name;

 move_uploaded_file($file["tmp_name"],$path);

 return "uploads/kyc/".$name;
}

$idFront = saveFile($_FILES["id_front"],"front");

$idBack = isset($_FILES["id_back"]) ? saveFile($_FILES["id_back"],"back") : null;

$selfie = saveFile($_FILES["selfie"],"selfie");

$stmt = $conn->prepare("
INSERT INTO user_verifications (user_id,id_front,id_back,selfie,status)
VALUES (?,?,?,?, 'pending')
ON DUPLICATE KEY UPDATE
id_front=?,id_back=?,selfie=?,status='pending'
");

$stmt->bind_param(
"issssss",
$user_id,$idFront,$idBack,$selfie,
$idFront,$idBack,$selfie
);

$stmt->execute();

echo json_encode([
 "status"=>"success",
 "message"=>"Documents submitted for review"
]);