<?php
require_once '../../config/config.php';
require_once '../helper/audit_log.php';
require_once '../email/send_message.php';
header('Content-Type: application/json');

try {
    $exam_id   = (int)($_POST['exam_id'] ?? 0);
    $staff_id  = (int)($_POST['staff_id'] ?? 0);
    $pattern_id= isset($_POST['pattern_id']) && $_POST['pattern_id'] !== '' ? (int)$_POST['pattern_id'] : null; // optional (legacy)
    $exam_subject_id = isset($_POST['exam_subject_id']) && $_POST['exam_subject_id'] !== '' ? (int)$_POST['exam_subject_id'] : 0; // required new
    $template_id = isset($_POST['template_id']) && $_POST['template_id'] !== '' ? (int)$_POST['template_id'] : null; // optional new
    $base_url  = isset($_POST['base_url']) ? trim((string)$_POST['base_url']) : '';
    $start_date= trim((string)($_POST['start_date'] ?? ''));
    $end_date  = trim((string)($_POST['end_date'] ?? ''));

    $errors = [];
    if ($exam_id <= 0)   $errors[] = 'exam_id required';
    if ($staff_id <= 0)  $errors[] = 'staff_id required';
    if ($start_date === '') $errors[] = 'start_date required';
    if ($end_date === '')   $errors[] = 'end_date required';
    if ($exam_subject_id <= 0) $errors[] = 'exam_subject_id required';
    if ($errors) { echo json_encode(['status'=>'error','message'=>implode(', ', $errors)]); exit; }

    // Basic date validation
    if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $start_date) || !preg_match('/^\d{4}-\d{2}-\d{2}$/', $end_date)) {
        echo json_encode(['status'=>'error','message'=>'Invalid date format (YYYY-MM-DD)']); exit;
    }

    // Allow assigning any active staff; no role restriction

    // Validate pattern if provided
    if ($pattern_id) {
        $chk = $pdo->prepare('SELECT COUNT(*) FROM question_patterns WHERE pattern_id = ?');
        $chk->execute([$pattern_id]);
        if ((int)$chk->fetchColumn() === 0) {
            throw new Exception('Invalid question pattern selected.');
        }
    }

    // Validate exam_subject and match exam
    $stEs = $pdo->prepare('SELECT exam_id FROM exam_subjects WHERE exam_subject_id = ?');
    $stEs->execute([$exam_subject_id]);
    $esRow = $stEs->fetch(PDO::FETCH_ASSOC);
    if (!$esRow) { throw new Exception('Invalid exam subject selected.'); }
    if ((int)$esRow['exam_id'] !== $exam_id) { throw new Exception('Selected subject does not belong to the chosen exam.'); }

    // Validate template if provided
    if ($template_id) {
        $chkT = $pdo->prepare('SELECT COUNT(*) FROM question_pattern_templates WHERE template_id = ?');
        $chkT->execute([$template_id]);
        if ((int)$chkT->fetchColumn() === 0) { throw new Exception('Invalid template selected.'); }
    }

    // Detect optional columns for forward-compat
    $hasExamSubject = false; $hasTemplate = false; $hasPattern = true;
    try { $c=$pdo->query("SHOW COLUMNS FROM qp_setter_assignments LIKE 'exam_subject_id'"); $hasExamSubject = $c && $c->rowCount()>0; } catch (Throwable $e) { $hasExamSubject=false; }
    try { $c=$pdo->query("SHOW COLUMNS FROM qp_setter_assignments LIKE 'template_id'"); $hasTemplate = $c && $c->rowCount()>0; } catch (Throwable $e) { $hasTemplate=false; }
    try { $c=$pdo->query("SHOW COLUMNS FROM qp_setter_assignments LIKE 'pattern_id'"); $hasPattern = $c && $c->rowCount()>0; } catch (Throwable $e) { $hasPattern=true; }

    $cols = ['exam_id','staff_id','start_date','end_date'];
    $vals = [$exam_id,$staff_id,$start_date,$end_date];
    if ($hasPattern) { $cols[]='pattern_id'; $vals[]=$pattern_id; }
    if ($hasExamSubject) { $cols[]='exam_subject_id'; $vals[]=$exam_subject_id; }
    if ($hasTemplate) { $cols[]='template_id'; $vals[]=$template_id; }
    $ph = implode(',', array_fill(0, count($cols), '?'));
    $sql = 'INSERT INTO qp_setter_assignments ('.implode(',', $cols).') VALUES ('.$ph.')';
    $stmt = $pdo->prepare($sql); $stmt->execute($vals);
    $id = (int)$pdo->lastInsertId();

    write_audit_log($pdo, [
        'module' => 'Question Papers',
        'action' => 'create',
        'entity_table' => 'qp_setter_assignments',
        'entity_id' => $id,
        'after_data' => compact('id','exam_id','staff_id','start_date','end_date','pattern_id','exam_subject_id','template_id'),
        'message' => 'QP Setter assignment created'
    ]);

    // Attempt to send notification email to the assigned setter (with login link)
    $email_status = null;
    try {
        // Fetch staff email and name
        $st = $pdo->prepare('SELECT first_name, last_name, email FROM staff WHERE staff_id = ?');
        $st->execute([$staff_id]);
        $staff = $st->fetch(PDO::FETCH_ASSOC);

        // Fetch exam name
        $se = $pdo->prepare('SELECT exam_name FROM exams WHERE exam_id = ?');
        $se->execute([$exam_id]);
        $exam = $se->fetch(PDO::FETCH_ASSOC);

        if ($staff && !empty($staff['email'])) {
            // Load template if available
            $tplStmt = $pdo->prepare("SELECT * FROM email_message_templates WHERE template_type = ? AND is_active = 1 ORDER BY id DESC LIMIT 1");
            $tplStmt->execute(['qp_setter_assigned']);
            $template = $tplStmt->fetch(PDO::FETCH_ASSOC);

            // Prepare variables
            $variables = [
                'setter_name' => trim(($staff['first_name'] ?? '').' '.($staff['last_name'] ?? '')),
                'exam_name'   => $exam['exam_name'] ?? ('Exam #'.$exam_id),
                'start_date'  => $start_date,
                'end_date'    => $end_date
            ];

            // Create a one-time login token for QP Setter portal
            $token = bin2hex(random_bytes(16));
            $expiresAt = date('Y-m-d H:i:s', time() + 60*60*24); // 24 hours
            $insTok = $pdo->prepare('INSERT INTO qp_setter_login_tokens (staff_id, assignment_id, token, expires_at) VALUES (?,?,?,?)');
            $insTok->execute([$staff_id, $id, $token, $expiresAt]);

            require_once __DIR__ . '/../../config/config.php';
            // Determine base URL priority: configured BASE_URL -> client-provided -> server-derived
            $derivedBase = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https://' : 'http://') . ($_SERVER['HTTP_HOST'] ?? 'localhost') . rtrim(dirname($_SERVER['SCRIPT_NAME'] ?? '/'), '/\\') . '/';
            $rootBase = defined('BASE_URL') ? BASE_URL : '';
            $chosenBase = $rootBase !== '' ? $rootBase : ($base_url !== '' ? $base_url : $derivedBase);
            if (substr($chosenBase, -1) !== '/') { $chosenBase .= '/'; }
            $loginLink = $chosenBase . 'qp-setter-login.php?token=' . urlencode($token);

            $subject = $template ? $template['subject_template'] : ('QP Setter Assignment - '.$variables['exam_name']);
            $message = $template ? $template['message_template'] : (
                "Dear {setter_name},\n\n".
                "You have been assigned as Question Paper Setter for {exam_name}.\n".
                "Assignment Window: {start_date} to {end_date}.\n\n".
                "Use this secure link to proceed (valid 24 hours):\n{login_link}\n\n".
                "After opening the link, you'll receive an OTP to complete login.\n\n".
                "Regards,\nCOE"
            );

            // Replace variables
            foreach ($variables as $k => $v) {
                $subject = str_replace('{'.$k.'}', $v, $subject);
                $message = str_replace('{'.$k.'}', $v, $message);
            }
            $subject = str_replace('{login_link}', $loginLink, $subject);
            $message = str_replace('{login_link}', $loginLink, $message);

            $email = new EmailSender($pdo);
            // Force the brand/header to show as Controller Of Examination
            $sendResult = $email->sendMessage($staff['email'], $subject, nl2br($message), $template['id'] ?? null, null, 'Controller Of Examination');
            $email_status = $sendResult['status'] ?? 'unknown';
        } else {
            $email_status = 'skipped_no_email';
        }
    } catch (Throwable $mailEx) {
        // Don't fail the main API for email issues; report status
        $email_status = 'error: '.$mailEx->getMessage();
    }

    echo json_encode([
        'status'=>'success',
        'message'=>'Assignment created',
        'data'=>['id'=>$id],
        'email_status' => $email_status
    ]);
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(['status'=>'error','message'=>$e->getMessage()]);
}
?>


