<?php
declare(strict_types=1);
namespace BranchAdmin\Controllers;

class BranchResultController extends BranchBaseController
{
    public function index(): void
    {
        requireBranchAdmin();
        $branchId = $this->getBranchId();
        $results = [];
        try {
            $stmt = $this->db->prepare("SELECT r.*, s.enrollment_no, u.name AS student_name, c.name AS course_name
                FROM branch_results r LEFT JOIN students s ON r.student_id = s.id LEFT JOIN users u ON s.user_id = u.id LEFT JOIN courses c ON r.course_id = c.id
                WHERE r.branch_id = :bid ORDER BY r.created_at DESC");
            $stmt->execute([':bid' => $branchId]);
            $results = $stmt->fetchAll() ?: [];
        } catch (\Throwable $e) {}
        $this->branchAdminView('results/index', ['title'=>'Manual Results','currentPage'=>'results','results'=>$results]);
    }

    public function create(): void
    {
        requireBranchAdmin();
        $branchId = $this->getBranchId();
        $students = [];
        try {
            $stmt = $this->db->prepare("SELECT s.*, u.name, u.email, u.phone, c.name AS course_name, c.subjects, c.duration FROM students s LEFT JOIN users u ON s.user_id=u.id LEFT JOIN courses c ON s.course_id=c.id WHERE s.branch_id=:bid AND s.status='active' ORDER BY u.name");
            $stmt->execute([':bid' => $branchId]);
            $students = $stmt->fetchAll() ?: [];
        } catch (\Throwable $e) {}
        $this->branchAdminView('results/create', ['title'=>'Create Result','currentPage'=>'results','students'=>$students]);
    }

    public function store(): void
    {
        requireBranchAdmin();
        $this->validateCsrf();
        flash('info', 'Please use the "Generate Certificate & Marksheet" menu for the new result workflow.');
        redirect(BASE_PATH . '/branch/cert-gen');
    }

    public function show(?int $id = null): void
    {
        requireBranchAdmin();
        if (!$id || $id <= 0) { flash('error', 'Invalid ID.'); redirect(BASE_PATH.'/branch/results'); }
        $branchId = $this->getBranchId();
        $stmt = $this->db->prepare("SELECT r.*, s.enrollment_no, u.name AS student_name, u.email, u.phone, s.father_name, s.dob, s.admission_date, c.name AS course_name, c.duration
            FROM branch_results r LEFT JOIN students s ON r.student_id = s.id LEFT JOIN users u ON s.user_id = u.id LEFT JOIN courses c ON r.course_id = c.id WHERE r.id=:id AND r.branch_id=:bid LIMIT 1");
        $stmt->execute([':id'=>$id, ':bid'=>$branchId]);
        $result = $stmt->fetch() ?: null;
        if (!$result) { flash('error', 'Result not found.'); redirect(BASE_PATH.'/branch/results'); }
        $this->branchAdminView('results/show', ['title'=>'Result: '.($result['student_name']??''),'currentPage'=>'results','result'=>$result,'subjects'=>[]]);
    }

    public function publish(?int $id = null): void
    {
        requireBranchAdmin();
        $this->validateCsrf();
        if (!$id || $id <= 0) { flash('error', 'Invalid ID.'); redirect(BASE_PATH.'/branch/results'); }
        try {
            $this->db->prepare("UPDATE branch_results SET status='published', published_at=NOW(), updated_at=NOW() WHERE id=:id")->execute([':id'=>$id]);
            flash('success', 'Result published.');
        } catch (\Throwable $e) { flash('error', 'Failed.'); }
        redirect(BASE_PATH.'/branch/results/'.$id);
    }

    public function delete(?int $id = null): void
    {
        requireBranchAdmin();
        $this->validateCsrf();
        if (!$id || $id <= 0) { flash('error', 'Invalid ID.'); redirect(BASE_PATH.'/branch/results'); }
        $branchId = $this->getBranchId();
        try {
            $this->db->prepare("DELETE FROM branch_results WHERE id=:id AND branch_id=:bid")->execute([':id'=>$id, ':bid'=>$branchId]);
            flash('success', 'Result deleted.');
        } catch (\Throwable $e) { flash('error', 'Failed.'); }
        redirect(BASE_PATH.'/branch/results');
    }
}
