<?php
/**
 * Standalone Registration API for RMSS
 * Handles capacity logic and SMS routing based on trialver
 */

// add_registration.php
// 1. Force errors to show in the browser/AJAX response temporarily
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
date_default_timezone_set('Asia/Singapore');

// 2. Custom logging function
function write_log($message) {
    $log_file = __DIR__ . '/debug.txt';
    $timestamp = date("Y-m-d H:i:s");
    file_put_contents($log_file, "[$timestamp] $message" . PHP_EOL, FILE_APPEND);
}

write_log("--- Script Started ---");
//write_log("Checking config file path...");

// add_registration.php
// 1. The log confirms it's arriving as form-urlencoded, so we use $_POST directly
// 1. Check if the bridge sent data as a JSON string wrapped in a POST key
$firstKey = !empty($_POST) ? array_key_first($_POST) : '';

if (str_starts_with($firstKey, '{"')) {
    // The data arrived as a JSON string in the key
    $decoded = json_decode($firstKey, true);
    
    //write_log("Full decoded: " . print_r($decoded, true));
    if (is_array($decoded)) {
        $_POST = $decoded; // Replace POST with the actual data
    }
}
// 2. Fallback for raw JSON body (php://input)
else if (empty($_POST)) {
    $content = file_get_contents("php://input");
    $decoded = json_decode($content, true);
    if (is_array($decoded)) {
        $_POST = $decoded;
    }
}
//write_log("Full POST: " . print_r($_POST, true));
// 3. Now access the token normally
$token = $_POST['recaptcha_token'] ?? '';

if (empty($token)) {
    write_log("Still missing token. Keys received: " . implode(', ', array_keys($_POST)));
    echo json_encode(["status" => 0, "message" => "Security token missing."]);
    exit;
} else {
    //write_log("Full token: " . print_r($_POST, true));
}

// --- 1. Dynamic CORS for Multiple Domains ---
$allowedOrigins = [
    'https://rmss.com.sg',
    'https://raymonds.sg',
    'https://www.rmss.com.sg', // It is safer to include the www version too
    'https://www.raymonds.sg'
];
require_once __DIR__ . '/../../scriptHelpers/db_config.php';
require_once __DIR__ . '/../../scriptHelpers/logHelper.php';
require_once __DIR__ . '/../../scriptHelpers/DBHelper.php';
require_once __DIR__ . '/../../scriptHelpers/SmsHelper.php';

/**
 * Validates Singapore mobile format
 */
function mobileOK(?string $m): bool {
    if (empty($m)) return false;
    $m = trim($m);
    return strlen($m) === 8 && ($m[0] === '9' || $m[0] === '8');
}

// 3. Initialize
DBHelper::init();
$db = new DBHelper();


// 4. Inputs Sanitization (Now that $_POST is populated correctly)
$trialver   = $_POST['ver'] ?? '2';

// Clean names and strings
$snameRaw = $_POST['sname'] ?? '';
$pnameRaw = $_POST['pname'] ?? '';

// This regex replaces underscores, hyphens, and any whitespace-like characters with a standard space
$pattern = '/[_\-\s]+/u'; 
$snameRaw = preg_replace($pattern, ' ', $snameRaw);
$pnameRaw = preg_replace($pattern, ' ', $pnameRaw);

// Final cleanup for non-printable characters
$sname = trim(preg_replace('/[\x00-\x1F\x7F]/u', '', $snameRaw));
$pname = trim(preg_replace('/[\x00-\x1F\x7F]/u', '', $pnameRaw));
$level      = preg_replace('/[\x00-\x1F\x7F]/u', '', $_POST['level'] ?? '');
$source     = preg_replace('/[\x00-\x1F\x7F]/u', '', $_POST['source'] ?? '');


// Sanitizing numbers (Using filter_var instead of filter_input because $_POST was modified)
$smobile    = filter_var($_POST['smobile'] ?? '', FILTER_SANITIZE_NUMBER_INT);
$pmobile    = filter_var($_POST['pmobile'] ?? '', FILTER_SANITIZE_NUMBER_INT);

// Sanitizing Class IDs (Handling the deprecated STRING filter)
$classids   = preg_replace('/[^a-zA-Z0-9,]/', '', $_POST['classid'] ?? '');

// Logical values
$isExisting = filter_var($_POST['isExisting'] ?? 0, FILTER_VALIDATE_INT) ?: 0;
$seat     = filter_var($_POST['seat'] ?? 1, FILTER_VALIDATE_INT) ?: 1;

try {
    if (!$trialver || !$classids) throw new Exception("Incomplete data.");

    $classIdArray = array_map('intval', explode(',', $classids));
    $cleanIds = implode(',', $classIdArray);

    // --- 5. DUPLICATE CHECK ---
    // Check if THIS student with THIS mobile has already registered for ANY of THESE classes
    $dupSql = "SELECT COUNT(*) as total 
               FROM `r1_trial` a 
               JOIN `r1_trial_schedule` b ON a.id = b.trial_id 
               WHERE a.studentname = " . DBHelper::Quote($sname) . " 
               AND a.smobile = " . DBHelper::Quote($smobile) . "
               AND b.schedule IN ($cleanIds)";
    
    $dupResult = $db->setQuery($dupSql)->execute()->loadAssoc();
    if ((int)$dupResult['total'] > 0) {
        write_log("Duplicates");
        throw new Exception("Registration already exists for these sessions.");
    }

    // --- 6. FETCH LESSON & LOCATION DATA ---
    /*
        $query = "
            SELECT l.id, l.isHP, l.isWS, l.isCC, l.day, l.topic, l.maxcap,
                loc.loc_desc AS venuestring
            FROM `r1_tlesson` AS l
            LEFT JOIN `r1_location` AS loc ON l.location = loc.location
            WHERE l.id IN ($cleanIds)
        ";
        $lessonlist = $db->setQuery($query)->execute()->loadObjectList();
        if (empty($lessonlist)) throw new Exception("Invalid classes.");

        // --- 7. CAPACITY CHECK (Seminar - ver 3 only) ---
        if ($trialver === '3') {
            foreach ($lessonlist as $lesson) {
                $checkSql = "SELECT SUM(seat) as total FROM r1_trial_schedule a 
                            JOIN r1_trial b ON a.trial_id = b.id 
                            WHERE a.schedule = " . (int)$lesson->id;
                $booked = $db->setQuery($checkSql)->execute()->loadAssoc();
                $currentBooked = (int)($booked['total'] ?? 0);
                
                if (($currentBooked + $seat) > (int)$lesson->maxcap) {
                    throw new Exception("Session '{$lesson->topic}' is fully booked.");
                }
            }
        }
    */
    $query = "
        SELECT l.id, l.isHP, l.isWS, l.isCC, l.day, l.schedule, l.topic, l.subject,l.sub,l.levelsub, l.maxcap, l.doclink,
               loc.loc_desc AS venuestring
        FROM `r1_tlesson` AS l
        LEFT JOIN `r1_location` AS loc ON l.location = loc.location
        WHERE l.id IN ($cleanIds)
    ";
    $lessonlist = $db->setQuery($query)->execute()->loadObjectList();
    //write_log("Classid:".$query);
    if (empty($lessonlist)) throw new Exception("Invalid classes.");

    // 7. CONSTRUCT LESSON AND MATERIAL STRINGS, SEAT, WORKSHOP
    $lessonItems = [];
    $materialItems = [];
    foreach ($lessonlist as $lesson) {
        // Build Lesson string: "Topic (Day/Time)"
        $lessonItems[] = $lesson->subject. " ". $lesson->schedule;
        
        // Build Material string if exists
        if (!empty($lesson->material)) {
            $materialItems[] = $lesson->doclink;
        }
    }
    $lessonString = implode("\n", $lessonItems);
    $materialString = !empty($materialItems) ? implode(", ", array_unique($materialItems)) : "N/A";
    $seatString = $seat==1 ? "$seat seat" : "$seat seats";

    // --- 8. DATABASE TRANSACTION ---
    $db->beginTransaction();
    $sqlMain = "INSERT INTO `r1_trial` (`date_time`, `studentname`, `smobile`, `parentname`, `pmobile`, `seat`,`source`,`level`, `isExisting`) 
                VALUES (NOW(), " . DBHelper::Quote($sname) . ", " . DBHelper::Quote($smobile) . ", 
                " . DBHelper::Quote($pname) . ", " . DBHelper::Quote($pmobile) . ", $seat,". DBHelper::Quote($source).",". DBHelper::Quote($level).", $isExisting)";
    $db->setQuery($sqlMain)->execute();
    //$transid = $db->setQuery("SELECT LAST_INSERT_ID()")->execute()->loadResult();
/*
    foreach ($classIdArray as $cid) {
        $db->setQuery("INSERT INTO `r1_trial_schedule` (`trial_id`, `schedule`) VALUES (1, $cid)")->execute();
    }

    $db->commit();

*/
// Use your new method
    $transid = $db->insertid();
    if ($transid > 0) {
        foreach ($lessonlist as $cid) {
            if  ($cid->id > 0) {
                $sqlSub = "INSERT INTO `r1_trial_schedule` (`trial_id`,`sub`,`levelsub`, `schedule`) VALUES ($transid, '$cid->sub', '$cid->levelsub', $cid->id)";
                $db->setQuery($sqlSub)->execute();
                //write_log("No Error: ".$transid);
                }
        }
        $db->commit();
    } else {
        $db->rollback();
        write_log("Error: No insert ID generated.");
    }

    // --- 9. SMS LOGIC ---
    $firstLesson = $lessonlist[0];
    $foundcc = false;
    foreach($lessonlist as $l) { if($l->isCC == 1) $foundcc = true; }

    if ($firstLesson->isHP == 1) $reftype = 'FREE_TRIAL';
    elseif ($foundcc) $reftype = 'CC_REG';
    elseif ($firstLesson->isWS == 2) $reftype = 'WS2_REG';
    else $reftype = 'WS_REG';

    if ($firstLesson->isHP == 1) $workshopString = 'TRIAL LESSON';
    elseif ($firstLesson->isWS == 1) $workshopString = 'FREE WORKSHOP';
    elseif ($firstLesson->isWS == 2) $workshopString = 'SEMINAR';
    else $workshopString = 'CRASH COURSE';


    // 8. SMS Dispatch
    $meta = ['reftype' => $reftype, 'refid' => date('Y-m-d'), 'now' => date('Y-m-d H:i:s')];
    $tags = [
        '#studentname' => $sname,
        '#parentname'  => $pname,
        '#startdate'   => $firstLesson->day,
        '#venue'       => $firstLesson->venuestring ?: 'RMSS Center',
        '#topic'       => $firstLesson->topic,
        '#schedule'    => $lessonString,   // <--- New Tag for Topic/Schedule
        '#material'    => $materialString, // <--- New Tag for Material URLs
        '#seat'        => $seatString, // <--- New Tag for SEAT
        '#workshop'    => $workshopString, // <--- New Tag for #workshop
    ];

    // Parent SMS (Always sent if mobile valid)
    $tplParent = $db->setQuery("SELECT smstext FROM `r1_smstemplate` WHERE `usertype` = 2 AND `type` = '$reftype'")->execute()->loadAssoc();
    if ($tplParent && mobileOK($pmobile)) {
        SmsHelper::send($db, (string)$pmobile, SmsHelper::generate($tplParent['smstext'], $tags), $meta);
    }

    // Student SMS (Only if trialver == 2)
    if ($trialver === '2') {
        $tplStudent = $db->setQuery("SELECT smstext FROM `r1_smstemplate` WHERE `usertype` = 1 AND `type` = '$reftype'")->execute()->loadAssoc();
        if ($tplStudent && mobileOK($smobile)) {
            SmsHelper::send($db, (string)$smobile, SmsHelper::generate($tplStudent['smstext'], $tags), $meta);
        }
    }

    echo json_encode(["status" => 1, "message" => "Registration successful."]);

} catch (Exception $e) {
    if (isset($db)) $db->rollback();
    write_log("ERROR: EXCEPTION");
    echo json_encode(["status" => 0, "message" => $e->getMessage()]);
}
