<?php
/**
 * Branch Certificate Generation - Pattern Integration Patch
 * 
 * This file shows how to modify your existing BranchCertGenController
 * to use the new Pattern System instead of the old template mapping.
 * 
 * Apply these changes to: /gmind/branch/Controllers/BranchCertGenController.php
 */

namespace BranchAdmin\Controllers;

use App\Helpers\Database;
use App\Helpers\DocumentGenerator;
use SuperAdmin\Controllers\SuperAdminPatternController;

class BranchCertGenControllerPatch
{
    /**
     * IN YOUR EXISTING download() METHOD - REPLACE THE PDF GENERATION PART
     * 
     * Find the section where DocumentGenerator is called and replace it with this code:
     */
    public function download(?int $certId = null)
    {
        // ... your existing validation code ...
        
        $db = Database::getInstance();
        
        // Load certificate with student + course info
        $cert = $db->selectOne("
            SELECT c.*, u.name as student_name, u.phone, u.email,
                   cr.name as course_name, cr.duration, cr.cert_pattern_id, cr.marksheet_pattern_id,
                   b.name as branch_name
            FROM certificates c
            LEFT JOIN users u ON c.student_id = u.id
            LEFT JOIN courses cr ON c.course_id = cr.id
            LEFT JOIN branches b ON c.branch_id = b.id
            WHERE c.id = ?
        ", [$certId]);
        
        if (!$cert) {
            $_SESSION['flash']['error'] = 'Certificate not found';
            header('Location: /branch/cert-gen');
            exit;
        }
        
        $docType = $_GET['type'] ?? 'certificate';
        
        $patternId = ($docType === 'certificate') 
            ? ($cert['cert_pattern_id'] ?? null)
            : ($cert['marksheet_pattern_id'] ?? null);
        
        if (!$patternId) {
            $defaultPattern = $db->selectOne("SELECT id FROM certificate_patterns WHERE is_default = 1 AND status = 'locked' LIMIT 1");
            $patternId = $defaultPattern['id'] ?? null;
        }
        
        if (!$patternId) {
            die('No pattern assigned to this course. Please ask Super Admin to assign a pattern.');
        }
        
        $pattern = $db->selectOne("SELECT * FROM certificate_patterns WHERE id = ? AND status = 'locked'", [$patternId]);
        if (!$pattern) {
            die('Pattern not found or not locked.');
        }
        
        $fields = $db->select("
            SELECT * FROM certificate_pattern_fields 
            WHERE pattern_id = ? AND doc_type = ? AND is_enabled = 1
            ORDER BY id ASC
        ", [$patternId, $docType]);
        
        $bgPath = ($docType === 'certificate')
            ? $pattern['cert_background_path']
            : $pattern['marksheet_background_path'];
        
        $fullBgPath = $_SERVER['DOCUMENT_ROOT'] . $bgPath;
        
        $subjects = [];
        if ($docType === 'marksheet') {
            $subjects = $db->select("
                SELECT subject_name as name, max_marks as max, obtained_marks as obtained
                FROM exam_results
                WHERE student_id = ? AND course_id = ?
                ORDER BY id ASC
            ", [$cert['student_id'], $cert['course_id']]) ?: [];
            
            if (empty($subjects)) {
                $courseSubj = $db->selectOne("SELECT subjects FROM courses WHERE id = ?", [$cert['course_id']]);
                if (!empty($courseSubj['subjects'])) {
                    $subjList = json_decode($courseSubj['subjects'], true);
                    if (is_array($subjList)) {
                        foreach ($subjList as $s) {
                            $subjects[] = [
                                'name' => $s['name'] ?? $s['subject_name'] ?? '',
                                'max' => $s['max_marks'] ?? $s['max'] ?? 100,
                                'obtained' => $s['obtained'] ?? 0
                            ];
                        }
                    }
                }
            }
        }
        
        $studentData = [
            'student_name'   => $cert['student_name'],
            'father_name'    => $cert['father_name'] ?? '',
            'enrollment_no'  => $cert['enrollment_no'] ?? '',
            'certificate_no' => $cert['certificate_no'] ?? ('CERT-' . $cert['id']),
            'course'         => $cert['course_name'],
            'branch_name'    => $cert['branch_name'],
            'duration'       => $cert['duration'],
            'date_of_issue'  => $cert['issue_date'] ?? date('d/m/Y'),
            'from_date'      => $cert['from_date'] ?? '',
            'to_date'        => $cert['to_date'] ?? '',
            'percentage'     => $cert['percentage'] ?? '',
            'grade'          => $cert['grade'] ?? '',
            'photo'          => $cert['photo'] ?? '',
            'qr_data'        => 'CERT:' . $cert['certificate_no'] . '|ENR:' . $cert['enrollment_no'],
            'subjects'       => $subjects
        ];
        
        try {
            $generator = new DocumentGenerator();
            $pdf = $generator->generateFromPattern([
                'pattern'    => $pattern,
                'fields'     => $fields,
                'student'    => $studentData,
                'doc_type'   => $docType,
                'bg_path'    => $fullBgPath,
                'is_preview' => false
            ]);
            
            $filename = $docType . '_' . preg_replace('/[^a-zA-Z0-9]/', '_', $cert['student_name']) . '.pdf';
            $pdf->Output('D', $filename);
            exit;
            
        } catch (\Exception $e) {
            die('PDF generation failed: ' . $e->getMessage());
        }
    }
}
