<?php
session_start();
require_once 'db.php';
header("Content-Type: application/json; charset=UTF-8");

ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/php_error.log');

require_once 'config.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['status' => 'error', 'message' => 'Invalid request method']);
    exit;
}

$uniqueId = $_POST['uniqueId'] ?? '';
if (!$uniqueId) {
    echo json_encode(['status' => 'error', 'message' => 'Missing registration number']);
    exit;
}

// Max file size (2 MB)
$maxFileSize = 2 * 1024 * 1024; // bytes

// Upload directory
$uploadDir = __DIR__ . "/uploads/";
if (!is_dir($uploadDir)) {
    mkdir($uploadDir, 0777, true);
}

// Validate Student Photo
if (!empty($_FILES['studentPhoto']['name'])) {
    if ($_FILES['studentPhoto']['size'] > $maxFileSize) {
        echo json_encode(['status' => 'error', 'message' => 'Student Photo must be less than 2 MB']);
        exit;
    }
    $photoName = time() . "_photo_" . basename($_FILES['studentPhoto']['name']);
    $photoPath = $uploadDir . $photoName;
    if (move_uploaded_file($_FILES['studentPhoto']['tmp_name'], $photoPath)) {
        $photoDbPath = "uploads/" . $photoName;
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Failed to upload student photo']);
        exit;
    }
} else {
    echo json_encode(['status' => 'error', 'message' => 'Student photo is required']);
    exit;
}

// Validate Aadhar Card
if (!empty($_FILES['aadharCard']['name'])) {
    if ($_FILES['aadharCard']['size'] > $maxFileSize) {
        echo json_encode(['status' => 'error', 'message' => 'Aadhar Card must be less than 2 MB']);
        exit;
    }
    $aadharName = time() . "_aadhar_" . basename($_FILES['aadharCard']['name']);
    $aadharPath = $uploadDir . $aadharName;
    if (move_uploaded_file($_FILES['aadharCard']['tmp_name'], $aadharPath)) {
        $aadharDbPath = "uploads/" . $aadharName;
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Failed to upload Aadhar card']);
        exit;
    }
} else {
    echo json_encode(['status' => 'error', 'message' => 'Aadhar card is required']);
    exit;
}

// Update database
$sql = "UPDATE students 
        SET photo_path = ?, aadhar_card_path = ?
        WHERE unique_reg_number = ?";

$stmt = $conn->prepare($sql);
if (!$stmt) {
    error_log("Prepare failed: " . $conn->error);
    echo json_encode(['status' => 'error', 'message' => 'Database error: prepare failed']);
    exit;
}

$stmt->bind_param("sss", $photoDbPath, $aadharDbPath, $uniqueId);

if ($stmt->execute()) {
    echo json_encode(['status' => 'success', 'message' => 'Documents uploaded successfully', 'uniqueId' => $uniqueId]);
} else {
    error_log("Execute failed: " . $stmt->error);
    echo json_encode(['status' => 'error', 'message' => 'Database error: execute failed']);
}

$stmt->close();
$conn->close();
