<?php
// api/upload_kyc.php - 接收身分證件上傳
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
error_reporting(0);
require_once 'db.php';

$user_id = isset($_POST['user_id']) ? intval($_POST['user_id']) : 0;
if ($user_id <= 0) die(json_encode(["status" => "error", "message" => "未登入"]));

if (!isset($_FILES['id_card']) || $_FILES['id_card']['error'] !== UPLOAD_ERR_OK) {
    die(json_encode(["status" => "error", "message" => "請確認是否已選擇圖片！"]));
}

$upload_dir = '../uploads/kyc/';
if (!is_dir($upload_dir)) @mkdir($upload_dir, 0777, true);

$file_ext = strtolower(pathinfo($_FILES['id_card']['name'], PATHINFO_EXTENSION));
$allowed = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
if (!in_array($file_ext, $allowed)) die(json_encode(["status" => "error", "message" => "僅支援圖片格式喔 (jpg, png)！"]));

$new_name = "kyc_" . $user_id . "_" . time() . "." . $file_ext;
$dest = $upload_dir . $new_name;

if (move_uploaded_file($_FILES['id_card']['tmp_name'], $dest)) {
    $stmt = $pdo->prepare("UPDATE users SET id_photo = ? WHERE id = ?");
    $stmt->execute(['uploads/kyc/' . $new_name, $user_id]);
    echo json_encode(["status" => "success", "message" => "🛡️ 證件上傳成功！請等待天啟者審核。"]);
} else {
    echo json_encode(["status" => "error", "message" => "檔案儲存失敗"]);
}
?>