<?php
namespace App\Controllers;

use App\Helpers\PromptBuilder;
use App\Services\HistoryService;
use Dompdf\Dompdf;
use PhpOffice\PhpWord\PhpWord;

class ExamController
{
    public function showForm()
    {
        include __DIR__ . '/../Views/form.php';
    }

    public function generate()
    {
        $input = $this->sanitizeArray($_POST);

        // enforce limits
        $input['objective_count'] = min((int)($input['objective_count'] ?? 0), MAX_OBJECTIVE);
        $input['sub_objective_count'] = min((int)($input['sub_objective_count'] ?? 0), MAX_SUBOBJECTIVE);
        $input['theory_count'] = min((int)($input['theory_count'] ?? 0), MAX_THEORY);

        $builder = new PromptBuilder($input);
        $system = $builder->systemMessage();
        $user = $builder->userMessage();

        $responseText = $this->callGroqApi($system, $user);

        // Remove all asterisks as requested
        $responseText = str_replace('*', '', $responseText);

        // store in session for export
        $_SESSION['last_exam'] = $responseText;
        $_SESSION['last_meta'] = $input;

        // persist generation history (local SQLite)
        try {
            $hs = new HistoryService();
            $hs->save($input, $responseText);
        } catch (\Exception $e) {
            // don't break flow on history errors
            error_log('History save error: ' . $e->getMessage());
        }

        include __DIR__ . '/../Views/exam.php';
    }

    protected function callGroqApi($system, $user)
    {
        $apiKey = GROQ_API_KEY;
        if (empty($apiKey)) {
            return "ERROR: Groq API key not configured. Set GROQ_API_KEY in environment.";
        }

        $payload = [
            'model' => GROQ_MODEL,
            'messages' => [
                ['role' => 'system', 'content' => $system],
                ['role' => 'user', 'content' => $user]
            ],
            'temperature' => 0.2,
            'max_tokens' => 4096
        ];

        $ch = curl_init('https://api.groq.com/openai/v1/chat/completions');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json',
            'Authorization: Bearer ' . $apiKey,
        ]);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
        $result = curl_exec($ch);
        $err = curl_error($ch);
        curl_close($ch);

        if ($err) {
            return "ERROR: cURL error: " . $err;
        }

        $data = json_decode($result, true);
        if (isset($data['error'])) {
            return 'ERROR: ' . json_encode($data['error']);
        }

        return $data['choices'][0]['message']['content'] ?? 'ERROR: no content returned';
    }

    public function downloadPdf()
    {
        if (empty($_SESSION['last_exam'])) {
            echo 'No generated exam in session.'; return;
        }
        $content = htmlspecialchars($_SESSION['last_exam']);

        // Check for premium code in last_meta for premium features
        $isPremium = false;
        if (!empty($_SESSION['last_meta']['premium_code']) && $_SESSION['last_meta']['premium_code'] === 'PREMIUM') {
            $isPremium = true;
        }

        $watermarkHtml = '';
        if (!$isPremium) {
            $watermarkHtml = '<div style="position: fixed; top:40%; left:15%; width:70%; text-align:center; transform:rotate(-30deg); font-size:48px; color:rgba(200,200,200,0.25); z-index:1000;">INSTANTQUESTIONS (Free)</div>';
        }

        $schoolName = $_SESSION['last_meta']['school_name'] ?? '';
        $session = ($_SESSION['last_meta']['exam_year'] ?? date('Y')) . ' ACADEMIC SESSION EXAMINATION';
        
        $headerHtml = $schoolName ? '<div style="text-align:center; font-weight:bold; font-size:16pt; text-transform:uppercase;">' . htmlspecialchars($schoolName) . '</div>' : '';
        $headerHtml .= '<div style="text-align:center; font-weight:bold; font-size:14pt; margin-bottom:1rem; text-transform:uppercase;">' . htmlspecialchars($session) . '</div>';

        $footerHtml = '<div style="position: fixed; bottom: 20px; left: 0px; right: 0px; text-align: center; font-size: 10pt; color: #555;">Developed by Polycarp Ukadilonu (cpcodes web)</div>';

        $html = '<div style="font-family: \'Times New Roman\', serif; font-size:12pt;">'
            . $watermarkHtml
            . $footerHtml
            . $headerHtml
            . '<pre style="white-space: pre-wrap;">' . $content . '</pre>'
            . '</div>';

        $dompdf = new Dompdf();
        $dompdf->loadHtml($html);
        $dompdf->setPaper('A4', 'portrait');
        $dompdf->render();
        $dompdf->stream('exam.pdf', ['Attachment' => 1]);
    }

    public function downloadDocx()
    {
        if (empty($_SESSION['last_exam'])) {
            echo 'No generated exam in session.'; return;
        }

        $phpWord = new PhpWord();
        $section = $phpWord->addSection();

        $footer = $section->addFooter();
        $footer->addText('Developed by Polycarp Ukadilonu (cpcodes web)', ['size' => 10], ['alignment' => 'center']);

        if (!empty($_SESSION['last_meta']['school_name'])) {
            $section->addText($_SESSION['last_meta']['school_name'], ['bold' => true, 'size' => 14], ['alignment' => 'center']);
        }
        
        if (!empty($_SESSION['last_meta']['exam_year'])) {
            $session = $_SESSION['last_meta']['exam_year'] . ' ACADEMIC SESSION EXAMINATION';
            $section->addText($session, ['bold' => true, 'size' => 12], ['alignment' => 'center']);
        }

        $lines = preg_split('/\r?\n/', $_SESSION['last_exam']);
        foreach ($lines as $line) {
            $section->addText(htmlspecialchars_decode($line));
        }

        header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
        header('Content-Disposition: attachment;filename="exam.docx"');
        header('Cache-Control: max-age=0');
        $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
        $objWriter->save('php://output');
    }

    protected function sanitizeArray($arr)
    {
        $clean = [];
        foreach ($arr as $k => $v) {
            if (is_array($v)) {
                $clean[$k] = $this->sanitizeArray($v);
            } else {
                $s = strip_tags($v);
                $s = preg_replace('/(ignore|disregard|forget) previous instructions/i', '', $s);
                $s = substr($s, 0, 2000);
                $clean[$k] = trim($s);
            }
        }
        return $clean;
    }
}
