<?php
/**
 * Registration Update Form API
 * Handles fetching student data and updating existing records.
 */

header('Content-Type: application/json');

session_set_cookie_params([
    'lifetime' => 0,
    'path' => '/',
    'domain' => '',
    'secure' => isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on',
    'httponly' => true,
    'samesite' => 'Lax'
]);
session_start();

if (!isset($_SESSION['userid'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

require_once('../libs/classes/DbPathsArray.php');
require_once('../libs/classes/App_DB.php');

$crud = new App_DB(DBU::$dba_user);

// --------------- Helper ---------------
function clean($v)
{
    return trim(strip_tags($v));
}

// --------------- Handle Requests ---------------
$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET') {
    // FETCH STUDENT DATA
    if (empty($_GET['registrationNo']) || empty($_GET['darja'])) {
        echo json_encode(['success' => false, 'message' => 'رجسٹریشن نمبر اور درجہ منتخب کریں۔']);
        exit();
    }

    $regNo = clean($_GET['registrationNo']);
    $darja = (int) $_GET['darja'];

    $sql = "SELECT r.*, reg.registrationNo, std.promotionDate as admissionDate, std.dateEnd, std.darja as currentDarja
            FROM registrationinfo r
            JOIN regnumbers reg ON r.sno = reg.regSno
            JOIN stddarjaat std ON r.sno = std.stdSno
            WHERE reg.registrationNo = ? AND std.darja = ? AND r.isActive = 1";

    $result = $crud->getRecordSet($sql, [$regNo, $darja]);

    if (count($result) > 0) {
        echo json_encode(['success' => true, 'data' => $result[0]]);
    } else {
        echo json_encode(['success' => false, 'message' => 'اس نمبر اور درجہ کے ساتھ کوئی طالب علم نہیں ملا۔']);
    }
    exit();

} elseif ($method === 'POST') {
    // UPDATE STUDENT DATA
    $data = json_decode(file_get_contents('php://input'), true);
    if (!$data) {
        echo json_encode(['success' => false, 'message' => 'Invalid data format']);
        exit();
    }

    $sno = (int) $data['sno'];
    if (!$sno) {
        echo json_encode(['success' => false, 'message' => 'Student ID is missing']);
        exit();
    }

    // Required fields check (matching saveRegistration.php)
    $required = [
        'stdName',
        'fatherName',
        'nationality',
        'dob',
        'qualification',
        'guirdianName',
        'darja',
        'cellNo',
        'fatherProfession',
        'gurdianCellNo',
        'permanentAddress',
        'presentAddress',
        'guirdianNameAuth',
        'guirdianFNameAuth',
        'relationShipWithGuirdian',
        'dateEnd',
        'admissionDate',
        'registrationNo'
    ];

    foreach ($required as $field) {
        if (empty($data[$field])) {
            echo json_encode(['success' => false, 'message' => "لازمی فیلڈ خالی ہے: {$field}"]);
            exit();
        }
    }

    $stdName = clean($data['stdName']);
    $fatherName = clean($data['fatherName']);
    $nationality = clean($data['nationality']);
    $dob = clean($data['dob']);
    $qualification = clean($data['qualification']);
    $guirdianName = clean($data['guirdianName']);
    $cellNo = clean($data['cellNo']);
    $fatherProfession = clean($data['fatherProfession']);
    $gurdianCellNo = clean($data['gurdianCellNo']);
    $permanentAddress = clean($data['permanentAddress']);
    $presentAddress = clean($data['presentAddress']);
    $guirdianNameAuth = clean($data['guirdianNameAuth']);
    $guirdianFNameAuth = clean($data['guirdianFNameAuth']);
    $guirdianSign = clean($data['guirdianSign'] ?? '');
    $relationShipWithGuirdian = clean($data['relationShipWithGuirdian']);
    $signNazim = clean($data['signNazim'] ?? '');
    $admissionDate = clean($data['admissionDate']);
    $dateEnd = clean($data['dateEnd']);
    $registrationNo = clean($data['registrationNo']);
    $contact_email = clean($data['contact_email'] ?? '');

    // Enforce Hijri Prefix (YYYY-MM-RegNo)
    $hijriParts = explode('-', $_SESSION['hijri']);
    $hijriPrefix = (count($hijriParts) >= 2) ? ($hijriParts[0] . '-' . $hijriParts[1] . '-') : '';
    if (!empty($hijriPrefix) && strpos($registrationNo, $hijriPrefix) !== 0) {
        $registrationNo = $hijriPrefix . $registrationNo;
    }
    $isLocal = (int) ($data['isLocal'] ?? 0);
    $nicOpt = (int) ($data['nicOpt'] ?? 0);
    $currentDarja = (int) ($data['currentDarja'] ?? 0); // Original darja searched
    $newDarja = (int) $data['darja']; // Updated darja if changed

    // NIC logic
    $stdNic = ($nicOpt === 1) ? clean($data['stdNic'] ?? '') : '0';
    $guirdianNic = ($nicOpt === 2) ? clean($data['guirdianNic'] ?? '') : '0';
    $formB = ($nicOpt === 3) ? clean($data['formB'] ?? '') : '0';

    // Transactional updates
    try {
        // 1. Update registrationinfo
        $sqlInfo = "UPDATE registrationinfo SET 
            stdName=?, fatherName=?, nationality=?, dob=?, qualification=?, guirdianName=?, 
            cellNo=?, fatherProfession=?, gurdianCellNo=?, permanentAddress=?, presentAddress=?, 
            guirdianNameAuth=?, guirdianFNameAuth=?, guirdianSign=?, stdNic=?, guirdianNic=?, 
            formB=?, relationShipWithGuirdian=?, signNazim=?, isLocal=?, contact_email=?
            WHERE sno = ?";

        $paramsInfo = [
            $stdName,
            $fatherName,
            $nationality,
            $dob,
            $qualification,
            $guirdianName,
            $cellNo,
            $fatherProfession,
            $gurdianCellNo,
            $permanentAddress,
            $presentAddress,
            $guirdianNameAuth,
            $guirdianFNameAuth,
            $guirdianSign,
            $stdNic,
            $guirdianNic,
            $formB,
            $relationShipWithGuirdian,
            $signNazim,
            $isLocal,
            $contact_email,
            $sno
        ];

        $crud->dbQuery($sqlInfo, $paramsInfo);

        // 2. Update regnumbers
        $crud->dbQuery("UPDATE regnumbers SET registrationNo = ? WHERE regSno = ?", [$registrationNo, $sno]);

        // 3. Update stddarjaat (update current darja record)
        $shoba_sno = $crud->getValue("SELECT shoba_sno FROM darjaat WHERE derjaCode = ?", [$newDarja]);
        $sqlStdDrjat = "UPDATE stddarjaat SET darja=?, promotionDate=?, dateEnd=?, shoba_sno=? 
                        WHERE stdSno=? AND darja=?";
        $crud->dbQuery($sqlStdDrjat, [$newDarja, $admissionDate, $dateEnd, $shoba_sno, $sno, $currentDarja]);

        // Handle Photo if present
        // Handle Photo: support new upload OR removal OR no change
        if (isset($data['photoBase64'])) {
            $base64Data = $data['photoBase64'];
            if ($base64Data === 'CLEAR') {
                // Explicit removal
                $crud->dbQuery("UPDATE registrationinfo SET stdPhoto = '' WHERE sno = ?", [$sno]);
            } elseif (!empty($base64Data) && strpos($base64Data, 'data:image') === 0) {
                // New photo provided
                if (preg_match('/^data:image\/(\w+);base64,/', $base64Data, $matches)) {
                    $ext = $matches[1];
                    $imgData = base64_decode(substr($base64Data, strpos($base64Data, ',') + 1));
                    $photoDir = '../uploaded/takephoto/';
                    if (!is_dir($photoDir)) {
                        mkdir($photoDir, 0755, true);
                    }
                    $fileName = 'std_' . time() . '_' . rand(1000, 9999) . '.' . $ext;
                    if (file_put_contents($photoDir . $fileName, $imgData)) {
                        $stdPhoto = 'takephoto/' . $fileName;
                        $crud->dbQuery("UPDATE registrationinfo SET stdPhoto = ? WHERE sno = ?", [$stdPhoto, $sno]);
                    } else {
                        error_log("Failed to write photo file: " . $photoDir . $fileName);
                    }
                }
            }
            // If $base64Data is empty string, it means 'no change', so do nothing.
        }

        echo json_encode(['success' => true, 'message' => 'ریکارڈ کامیابی سے اپ ڈیٹ ہو گیا۔']);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => 'اپ ڈیٹ کے دوران خرابی آئی: ' . $e->getMessage()]);
    }
    exit();
}
