<?php
require_once('../config.php');

header('Content-Type: application/json');
$response = [
    'uploaded_files' => [],
    'success' => false,
    'message' => ''
];

$save_front_name = "";
$save_back_name  = "";

if (!empty($_FILES['screenshot'])) {
    $allSuccess = true;

    foreach ($_FILES['screenshot']['tmp_name'] as $key => $tmp_name) {
        $fileName = $_POST['author_card_no']. "_idcard_" . time() ."_". $key . ".png";
        $uploadPath = "../../uploads/id-card/" . $fileName;

        if (move_uploaded_file($tmp_name, $uploadPath)) {
            $response['uploaded_files'][] = $fileName;
            if ($key == 0) $save_front_name = $fileName;
            if ($key == 1) $save_back_name  = $fileName;

        } else {
            $allSuccess = false;
            $response['uploaded_files'][] = "Failed for index $key";
        }
    }
    if ($allSuccess) {
        $select_author     = $_POST['select_author'] ?? '';
        $author_name       = $_POST['author_name'] ?? '';
        $author_card_no    = $_POST['author_card_no'] ?? '';
        $author_cissuedate = $_POST['author_cissuedate'] ?? '';
        $author_cexpdate   = $_POST['author_cexpdate'] ?? '';

        // 🔹 Insert data
        $post_form_data = array(
            "CardUser"     => $select_author,
            "CardUserName" => $author_name,
            "CardNo"       => $author_card_no,
            "CardIssue"    => $author_cissuedate,
            "CardValidity" => $author_cexpdate,
            "CardCreated"  => $the_time,
            "CardFront"    => $save_front_name,
            "CardBack"     => $save_back_name,
            "CardAdmin"    => getSingleValue('admin_user', 'admin_security_key', $_COOKIE['Google_SLKA'], 'admin_id'),
        );

        if (InsertData('mahamudfutureit_idcard', $post_form_data)) {
            $response['success'] = true;
            $response['message'] = "All files uploaded & database updated";
            $response['redirect'] = "writer-id-cards.php";
        } else {
            $response['message'] = "Files uploaded but database insert failed";
        }

    } else {
        $response['message'] = "Some files failed";
    }

} else {
    $response['message'] = "No screenshot received.";
}

echo json_encode($response);
exit;
