<?php
/**
 * Save Registration API
 * Handles new student registration via AJAX POST (JSON body).
 * Inserts into: registrationinfo, regnumbers, stddarjaat
 */

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));
}

// --------------- Parse input ---------------
$data = json_decode(file_get_contents('php://input'), true);
if (!$data) {
    $data = $_POST; // fallback for multipart (photo upload)
}

// Required fields
$required = [
    'stdName',
    'fatherName',
    'nationality',
    'dob',
    'qualification',
    'guirdianName',
    'darja',
    'cellNo',
    'fatherProfession',
    'gurdianCellNo',
    'permanentAddress',
    'presentAddress',
    'guirdianNameAuth',
    'guirdianFNameAuth',
    'relationShipWithGuirdian',
    'dateEnd',
    'admissionDate',
    'admissionNo',
    'registrationNo'
];

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

// Sanitize
$stdName = clean($data['stdName']);
$fatherName = clean($data['fatherName']);
$nationality = clean($data['nationality']);
$dob = clean($data['dob']);
$qualification = clean($data['qualification']);
$guirdianName = clean($data['guirdianName']);
$darja = (int) $data['darja'];
$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']);
$admissionNo = clean($data['admissionNo']);
$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 = isset($data['isLocal']) ? (int) $data['isLocal'] : 0;
$nicOpt = (int) ($data['nicOpt'] ?? 0);

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

// ---- Photo: handle base64 from webcam OR filename from session ----
$stdPhoto = '';
if (!empty($data['photoBase64'])) {
    // Decode and save webcam capture
    $base64Data = $data['photoBase64'];
    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;
        file_put_contents($photoDir . $fileName, $imgData);
        $stdPhoto = 'takephoto/' . $fileName;
    }
} elseif (!empty($_SESSION['photo'])) {
    $stdPhoto = $_SESSION['photo'];
}

// ---- Check duplicate registrationNo ----
$existsRegNo = $crud->getRecordSet("SELECT registrationNo FROM regnumbers WHERE registrationNo = ?", [$registrationNo]);
if (count($existsRegNo) > 0) {
    echo json_encode(['success' => false, 'message' => 'رجسٹریشن نمبر پہلے سے موجود ہے۔ براہ کرم تبدیل کریں۔']);
    exit();
}

// ---- Check duplicate student ----
$existsStd = $crud->getRecordSet(
    "SELECT sno FROM registrationinfo WHERE stdName = ? AND fatherName = ? AND dob = ?",
    [$stdName, $fatherName, $dob]
);
if (count($existsStd) > 0) {
    echo json_encode(['success' => false, 'message' => 'یہ طالب علم پہلے ہی سے داخل شدہ ہے۔']);
    exit();
}

// ---- Insert into registrationinfo ----
$sqlSave = "INSERT INTO registrationinfo 
    (stdName, fatherName, nationality, dob, qualification, guirdianName, cellNo, fatherProfession, gurdianCellNo,
     permanentAddress, presentAddress, guirdianNameAuth, guirdianFNameAuth, guirdianSign, stdNic, guirdianNic, formB,
     relationShipWithGuirdian, signNazim, admissionNo, stdPhoto, isLocal, contact_email, isActive)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1)";

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

$inserted = $crud->dbQuery($sqlSave, $params);
if (!$inserted) {
    echo json_encode(['success' => false, 'message' => 'ڈیٹا محفوظ کرنے میں خرابی آئی۔ (registrationinfo)']);
    exit();
}

$regSno = $crud->getValue("SELECT sno FROM registrationinfo ORDER BY sno DESC LIMIT 1");

// ---- Insert into regnumbers ----
$sqlRegNo = "INSERT INTO regnumbers (registrationNo, RollNumber, regSno) VALUES (?, ?, ?)";
$inserted2 = $crud->dbQuery($sqlRegNo, [$registrationNo, $admissionNo, $regSno]);
if (!$inserted2) {
    echo json_encode(['success' => false, 'message' => 'ڈیٹا محفوظ کرنے میں خرابی آئی۔ (regnumbers)']);
    exit();
}

// ---- Get shoba_sno from darjaat ----
$shoba_sno = $crud->getValue("SELECT shoba_sno FROM darjaat WHERE derjaCode = ?", [$darja]);

// ---- Insert into stddarjaat ----
$sqlStdDrjat = "INSERT INTO stddarjaat (stdSno, darja, isCurrent, promotionDate, dateEnd, shoba_sno)
                VALUES (?, ?, 1, ?, ?, ?)";
$inserted3 = $crud->dbQuery($sqlStdDrjat, [$regSno, $darja, $admissionDate, $dateEnd, $shoba_sno]);
if (!$inserted3) {
    echo json_encode(['success' => false, 'message' => 'ڈیٹا محفوظ کرنے میں خرابی آئی۔ (stddarjaat)']);
    exit();
}

// Clear session photo
$_SESSION['photo'] = '';

echo json_encode([
    'success' => true,
    'message' => 'طالب علم کا اندراج کامیابی سے مکمل ہو گیا۔',
    'sno' => $regSno,
    'regNo' => $registrationNo
]);
