<?php
require_once "../database.php";
header('Content-Type: application/json');

// Validate inputs
if (!isset($_POST['email'], $_FILES['result_image'], $_FILES['result_pdf'])) {
    echo json_encode(["status" => "error", "message" => "Missing required fields"]);
    exit;
}

$email = $_POST['email'];
$image = $_FILES['result_image'];
$pdf = $_FILES['result_pdf'];

// Resolve user ID from email
$stmt = $conn->prepare("SELECT id FROM users WHERE email = :email");
$stmt->execute([':email' => $email]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$user) {
    echo json_encode(["status" => "error", "message" => "User not found"]);
    exit;
}

$user_id = $user['id'];

// Set upload path
$uploadDir = "../../uploads/results/";
if (!is_dir($uploadDir)) {
    mkdir($uploadDir, 0777, true);
}

// Debug upload errors
function getFileUploadError($file) {
    $errors = [
        UPLOAD_ERR_OK => 'No error',
        UPLOAD_ERR_INI_SIZE => 'File too large (php.ini)',
        UPLOAD_ERR_FORM_SIZE => 'File too large (form)',
        UPLOAD_ERR_PARTIAL => 'Partial upload',
        UPLOAD_ERR_NO_FILE => 'No file uploaded',
        UPLOAD_ERR_NO_TMP_DIR => 'No temp directory',
        UPLOAD_ERR_CANT_WRITE => 'Failed to write to disk',
        UPLOAD_ERR_EXTENSION => 'Upload stopped by extension',
    ];
    return $errors[$file['error']] ?? 'Unknown error';
}

if ($image['error'] !== UPLOAD_ERR_OK || $pdf['error'] !== UPLOAD_ERR_OK) {
    echo json_encode([
        "status" => "error",
        "message" => "Upload error — Image: " . getFileUploadError($image) . 
                     " | PDF: " . getFileUploadError($pdf)
    ]);
    exit;
}

// Generate secure hash for file names
$imageHash = substr(md5_file($image['tmp_name']), 0, 16);
$pdfHash = substr(md5_file($pdf['tmp_name']), 0, 16);

$imagePath = $uploadDir . "{$imageHash}_image_" . basename($image['name']);
$pdfPath = $uploadDir . "{$pdfHash}_pdf_" . basename($pdf['name']);

// Move files
if (move_uploaded_file($image['tmp_name'], $imagePath) &&
    move_uploaded_file($pdf['tmp_name'], $pdfPath)) {

    // Serve via hashed route
    $baseUrl = "https://schoolmata.com.ng/results/";
    $imageUrl = $baseUrl . $imageHash . "?type=image";
    $pdfUrl = $baseUrl . $pdfHash . "?type=pdf";

    // Save to database
    $insert = $conn->prepare("INSERT INTO admin_results (user_id, result_image, result_pdf) VALUES (:user_id, :result_image, :result_pdf)");
    $success = $insert->execute([
        ':user_id' => $user_id,
        ':result_image' => $imageUrl,
        ':result_pdf' => $pdfUrl
    ]);

    if ($success) {
        echo json_encode(["status" => "success", "message" => "Result uploaded successfully"]);
    } else {
        echo json_encode(["status" => "error", "message" => "Database insert failed"]);
    }
} else {
    echo json_encode([
        "status" => "error",
        "message" => "File upload failed"
    ]);
}
?>
