<?php
/**
 * Branch Document Download Controller — FIXED for Pattern System
 * 
 * Upload to: /gmind/branch/Controllers/BranchDocumentController.php
 *            (overwrite existing if any)
 * 
 * OR copy download() method into your existing controller.
 */

namespace BranchAdmin\Controllers;

use BranchAdmin\Controllers\BranchBaseController;

class BranchDocumentController extends BranchBaseController
{
    /**
     * Download a generated certificate/marksheet PDF
     */
    public function download(?int $id = null): void
    {
        requireBranchAdmin();
        $this->validateCsrf();

        if (!$id || $id <= 0) {
            flash('error', 'Invalid document ID.');
            redirect(BASE_PATH . '/branch/documents');
        }

        $branchId = $_SESSION['branch_id'] ?? 0;

        $stmt = $this->db->prepare(
            "SELECT c.*,
                    COALESCE(c.student_name, u.name, 'Unknown') AS student_name,
                    t.name AS template_name, t.type AS doc_type
             FROM certificates c
             LEFT JOIN students s ON c.student_id = s.id
             LEFT JOIN users u ON s.user_id = u.id
             LEFT JOIN certificate_templates t ON c.template_id = t.id
             WHERE c.id = :id AND c.branch_id = :bid LIMIT 1"
        );
        $stmt->execute([':id' => $id, ':bid' => $branchId]);
        $doc = $stmt->fetch() ?: null;

        if (!$doc) {
            flash('error', 'Document not found or access denied.');
            redirect(BASE_PATH . '/branch/documents');
        }

        if ($doc['status'] !== 'generated') {
            flash('error', 'Document is not yet approved/generated. Status: ' . $doc['status']);
            redirect(BASE_PATH . '/branch/documents');
        }

        $pdfPath = $doc['pdf_path'] ?? '';

        if (empty($pdfPath)) {
            flash('error', 'PDF file not found. Please contact Super Admin to regenerate.');
            redirect(BASE_PATH . '/branch/documents');
        }

        // ✅ FIX: Try multiple paths to find the PDF file
        $candidates = [
            $pdfPath,
            $_SERVER['DOCUMENT_ROOT'] . $pdfPath,
            $_SERVER['DOCUMENT_ROOT'] . '/' . ltrim($pdfPath, '/'),
            rtrim($_SERVER['DOCUMENT_ROOT'], '/') . $pdfPath,
            $_SERVER['DOCUMENT_ROOT'] . '/gmind' . $pdfPath,
            '/home/advaysin/public_html' . $pdfPath,
            '/home/advaysin/public_html/gmind' . $pdfPath,
        ];

        // If path doesn't start with /, prepend it
        if ($pdfPath[0] !== '/') {
            $candidates[] = $_SERVER['DOCUMENT_ROOT'] . '/' . $pdfPath;
            $candidates[] = '/home/advaysin/public_html/' . $pdfPath;
            $candidates[] = '/home/advaysin/public_html/gmind/' . $pdfPath;
        }

        $filePath = null;
        foreach ($candidates as $cand) {
            if (file_exists($cand) && is_readable($cand)) {
                $filePath = $cand;
                break;
            }
        }

        if (!$filePath) {
            error_log("PDF not found. Stored path: {$pdfPath}. Tried: " . implode(' | ', $candidates));
            flash('error', 'PDF file not found on server. Please contact Super Admin.');
            redirect(BASE_PATH . '/branch/documents');
        }

        $fileName = basename($filePath);
        $fileSize = filesize($filePath);

        $studentName = $doc['student_name'] ?? 'student';
        $studentName = preg_replace('/[^a-zA-Z0-9]/', '_', $studentName);
        $downloadName = $doc['doc_type'] . '_' . $studentName . '_' . $doc['certificate_no'] . '.pdf';

        // Send file to browser
        header('Content-Description: File Transfer');
        header('Content-Type: application/pdf');
        header('Content-Disposition: attachment; filename="' . $downloadName . '"');
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
        header('Content-Length: ' . $fileSize);

        while (ob_get_level()) {
            ob_end_clean();
        }

        readfile($filePath);
        exit;
    }

    /**
     * List all documents for this branch
     */
    public function index(): void
    {
        requireBranchAdmin();

        $branchId = $_SESSION['branch_id'] ?? 0;
        $statusFilter = trim($_GET['status'] ?? '');

        $sql = "SELECT c.*,
                       COALESCE(c.student_name, u.name, 'Unknown') AS student_name,
                       s.enrollment_no,
                       t.name AS template_name, t.type AS doc_type
                FROM certificates c
                LEFT JOIN students s ON c.student_id = s.id
                LEFT JOIN users u ON s.user_id = u.id
                LEFT JOIN certificate_templates t ON c.template_id = t.id
                WHERE c.branch_id = :bid";
        $params = [':bid' => $branchId];

        if ($statusFilter && in_array($statusFilter, ['pending_approval', 'generated', 'rejected', 'cancelled'], true)) {
            $sql .= " AND c.status = :status";
            $params[':status'] = $statusFilter;
        }
        $sql .= " ORDER BY c.created_at DESC";

        $stmt = $this->db->prepare($sql);
        $stmt->execute($params);
        $documents = $stmt->fetchAll() ?: [];

        $stats = ['pending' => 0, 'generated' => 0, 'rejected' => 0, 'total' => count($documents)];
        foreach ($documents as $d) {
            $status = $d['status'] ?? '';
            if ($status === 'pending_approval') $stats['pending']++;
            elseif ($status === 'generated') $stats['generated']++;
            elseif ($status === 'rejected') $stats['rejected']++;
        }

        $this->branchView('documents/index', [
            'title'        => 'My Documents',
            'currentPage'  => 'documents',
            'documents'    => $documents,
            'statusFilter' => $statusFilter,
            'stats'        => $stats,
        ]);
    }

    /**
     * Preview a generated PDF in browser
     */
    public function preview(?int $id = null): void
    {
        requireBranchAdmin();

        if (!$id || $id <= 0) {
            flash('error', 'Invalid document ID.');
            redirect(BASE_PATH . '/branch/documents');
        }

        $branchId = $_SESSION['branch_id'] ?? 0;

        $stmt = $this->db->prepare(
            "SELECT * FROM certificates WHERE id = :id AND branch_id = :bid LIMIT 1"
        );
        $stmt->execute([':id' => $id, ':bid' => $branchId]);
        $doc = $stmt->fetch() ?: null;

        if (!$doc) {
            flash('error', 'Document not found.');
            redirect(BASE_PATH . '/branch/documents');
        }

        if ($doc['status'] !== 'generated') {
            flash('error', 'Document not yet approved.');
            redirect(BASE_PATH . '/branch/documents');
        }

        $pdfPath = $doc['pdf_path'] ?? '';
        if (empty($pdfPath)) {
            flash('error', 'PDF file not found.');
            redirect(BASE_PATH . '/branch/documents');
        }

        $candidates = [
            $pdfPath,
            $_SERVER['DOCUMENT_ROOT'] . $pdfPath,
            $_SERVER['DOCUMENT_ROOT'] . '/' . ltrim($pdfPath, '/'),
            rtrim($_SERVER['DOCUMENT_ROOT'], '/') . $pdfPath,
            $_SERVER['DOCUMENT_ROOT'] . '/gmind' . $pdfPath,
            '/home/advaysin/public_html' . $pdfPath,
            '/home/advaysin/public_html/gmind' . $pdfPath,
        ];

        $filePath = null;
        foreach ($candidates as $cand) {
            if (file_exists($cand) && is_readable($cand)) {
                $filePath = $cand;
                break;
            }
        }

        if (!$filePath) {
            flash('error', 'PDF file not found on server.');
            redirect(BASE_PATH . '/branch/documents');
        }

        header('Content-Type: application/pdf');
        header('Content-Disposition: inline; filename="' . basename($filePath) . '"');
        header('Content-Length: ' . filesize($filePath));
        while (ob_get_level()) ob_end_clean();
        readfile($filePath);
        exit;
    }
}
