<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// omr_test.php
session_start();
require_once __DIR__ . '/config/db.php';
require_once __DIR__ . '/vendor/autoload.php';

use Dompdf\Dompdf;

$detected_answers = "";
$result = null;
$pdfWebPath = "";

/* -------------------------------
   HANDLE OMR UPLOAD
-------------------------------- */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['omr_image'])) {

    ob_start();
    include 'api_scan_omr.php';
    $output = ob_get_clean();

    $detected_answers = trim($output);
    $answers = array_values(array_filter(explode(",", $detected_answers)));

    /* -------------------------------
       QUESTION → STYLE MAP (20)
    -------------------------------- */
    $question_map = [
        1=>'Visual',2=>'Auditory',3=>'Kinesthetic',4=>'Reflective',5=>'Active',
        6=>'Visual',7=>'Auditory',8=>'Kinesthetic',9=>'Reflective',10=>'Active',
        11=>'Visual',12=>'Auditory',13=>'Kinesthetic',14=>'Reflective',15=>'Active',
        16=>'Visual',17=>'Auditory',18=>'Kinesthetic',19=>'Reflective',20=>'Active'
    ];

    $option_weight = ['A'=>1,'B'=>2,'C'=>3,'D'=>2];

    $style_score = [
        'Visual'=>0,
        'Auditory'=>0,
        'Kinesthetic'=>0,
        'Reflective'=>0,
        'Active'=>0
    ];

    foreach ($answers as $i => $opt) {
        $q = $i + 1;
        if (!isset($question_map[$q])) continue;
        $style_score[$question_map[$q]] += $option_weight[$opt] ?? 0;
    }

    arsort($style_score);
    $styles = array_keys($style_score);

    $primary = $styles[0];
    $secondary = $styles[1];

    /* -------------------------------
       STUDENT CONTEXT
    -------------------------------- */
    $student_roll = $_GET['roll'] ?? 'UNKNOWN';
    $student_name = $_GET['name'] ?? 'Student';

    /* -------------------------------
       GENERATE PDF
    -------------------------------- */
    $dompdf = new Dompdf();

    ob_start();
    ?>
    <h2>RS Learning Lab</h2>
    <h3>Learning Style Report</h3>

    <p><strong>Name:</strong> <?= htmlspecialchars($student_name) ?></p>
    <p><strong>Roll No:</strong> <?= htmlspecialchars($student_roll) ?></p>

    <p><strong>Primary Style:</strong> <?= $primary ?></p>
    <p><strong>Secondary Style:</strong> <?= $secondary ?></p>

    <h3>Scores</h3>
    <ul>
        <?php foreach ($style_score as $k=>$v): ?>
            <li><?= $k ?> : <?= $v ?></li>
        <?php endforeach; ?>
    </ul>

    <p style="margin-top:40px;">RS Learning Lab – Learning Behaviour Platform</p>

    <?php
    $html = ob_get_clean();

    $dompdf->loadHtml($html);
    $dompdf->setPaper('A4');
    $dompdf->render();

    $pdfDir = __DIR__ . '/generated_pdfs/';
    if (!is_dir($pdfDir)) {
        mkdir($pdfDir, 0777, true);
    }

    $pdfFile = $pdfDir . $student_roll . '_learning_style.pdf';

    file_put_contents($pdfFile, $dompdf->output());

    // Web path for download
    $pdfWebPath = "generated_pdfs/" . $student_roll . "_learning_style.pdf";

    /* -------------------------------
       SAVE TO DATABASE
    -------------------------------- */

    // check if record already exists
    $check = $pdo->prepare("SELECT id FROM learning_style_results WHERE student_roll=?");
    $check->execute([$student_roll]);

    if ($check->rowCount() > 0) {

        $stmt = $pdo->prepare("
        UPDATE learning_style_results
        SET student_name=?, primary_style=?, secondary_style=?, scores_json=?, pdf_path=?
        WHERE student_roll=?
        ");

        $stmt->execute([
            $student_name,
            $primary,
            $secondary,
            json_encode($style_score),
            $pdfWebPath,
            $student_roll
        ]);

    } else {

        $stmt = $pdo->prepare("
        INSERT INTO learning_style_results
        (student_roll, student_name, primary_style, secondary_style, scores_json, pdf_path)
        VALUES (?,?,?,?,?,?)
        ");

        $stmt->execute([
            $student_roll,
            $student_name,
            $primary,
            $secondary,
            json_encode($style_score),
            $pdfWebPath
        ]);
    }

    $result = true;
}
?>

<!DOCTYPE html>
<html>
<head>
<title>OMR Scan</title>

<style>
body{
background:#0b1020;
color:#fff;
font-family:Arial;
padding:30px
}

.card{
background:#111827;
padding:25px;
border-radius:12px;
max-width:700px;
margin:auto
}

.btn{
background:#0ea5e9;
padding:10px 16px;
border:none;
border-radius:8px;
color:#fff;
cursor:pointer
}

.success{
margin-top:20px;
color:#22c55e;
font-weight:bold
}

</style>
</head>

<body>

<div class="card">

<h2>OMR Scan</h2>

<form method="POST" enctype="multipart/form-data">

<input type="file" name="omr_image" required>

<br><br>

<button class="btn">Scan & Generate PDF</button>

</form>

<?php if ($result): ?>

<hr>

<p class="success">✅ Learning style report generated</p>

<a href="<?= $pdfWebPath ?>" target="_blank" class="btn">
Download PDF
</a>

<?php endif; ?>

</div>

</body>
</html>