<?php
/**
 * SmartForex Engine - KYC Document Upload Endpoint
 */
session_start();
if (!isset($_SESSION['user_id'])) { exit(json_encode(['status' => 'error', 'message' => 'Unauthorized'])); }

define('DB_HOST', 'localhost');
define('DB_NAME', 'rakshita_relay');
define('DB_USER', 'rakshita_relay');
define('DB_PASS', 'rehman@169');

try {
    $pdo = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=utf8mb4", DB_USER, DB_PASS);
} catch (PDOException $e) { exit; }

if (isset($_FILES['kyc_doc'])) {
    $ext = pathinfo($_FILES['kyc_doc']['name'], PATHINFO_EXTENSION);
    $filename = 'kyc_' . $_SESSION['user_id'] . '_' . time() . '.' . $ext;
    $target = '../uploads/' . $filename;
    
    if(!is_dir('../uploads/')) { mkdir('../uploads/', 0777, true); }

    if (move_uploaded_file($_FILES['kyc_doc']['tmp_name'], $target)) {
        $stmt = $pdo->prepare("UPDATE users SET kyc_status = 'pending', kyc_document = ? WHERE id = ?");
        $stmt->execute([$filename, $_SESSION['user_id']]);
        echo json_encode(['status' => 'success', 'message' => 'Document submitted successfully. Status: Pending Approval.']);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Upload handling aborted.']);
    }
}
exit;