<?php
/**
 * Super Admin Document Approval - Pattern Integration Patch
 * 
 * Modify your SuperAdminDocumentController::approve() method
 * to use the new Pattern System for PDF generation.
 * 
 * Apply to: /gmind/super-admin/Controllers/SuperAdminDocumentController.php
 * 
 * In approve() method, REPLACE the PDF generation block with this code.
 */

// In your approve() method, replace the DocumentGenerator call with:

/*
=============================================================================
// GET PATTERN FROM CERTIFICATE OR COURSE
=============================================================================
$patternId = $cert['pattern_id'] ?? null;

// Fallback to course's pattern
if (!$patternId) {
    $coursePattern = $db->selectOne("
        SELECT cert_pattern_id, marksheet_pattern_id 
        FROM courses WHERE id = ?
    ", [$cert['course_id']]);
    $patternId = $coursePattern['cert_pattern_id'] ?? null;
}

// Fallback to default pattern
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) {
    $_SESSION['flash']['error'] = 'No pattern assigned. Assign a pattern to the course first.';
    header('Location: /super-admin/documents');
    exit;
}

// Load pattern
$pattern = $db->selectOne("SELECT * FROM certificate_patterns WHERE id = ? AND status = 'locked'", [$patternId]);

// GENERATE BOTH CERTIFICATE AND MARKSHEET PDFs
$docTypes = ['certificate', 'marksheet'];
$generatedPaths = [];

foreach ($docTypes as $docType) {
    $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;
    
    // Skip if no background
    if (!file_exists($fullBgPath)) continue;
    
    // Load subjects for marksheet
    $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
                        ];
                    }
                }
            }
        }
    }
    
    // Build student data
    $studentData = [
        'student_name'   => $cert['student_name'] ?? $cert['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'  => 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'] ?? $cert['id']),
        'subjects'       => $subjects
    ];
    
    // Generate PDF
    $generator = new DocumentGenerator();
    $pdf = $generator->generateFromPattern([
        'pattern'    => $pattern,
        'fields'     => $fields,
        'student'    => $studentData,
        'doc_type'   => $docType,
        'bg_path'    => $fullBgPath,
        'is_preview' => false
    ]);
    
    // Save to file
    $uploadDir = $_SERVER['DOCUMENT_ROOT'] . '/uploads/certificates/';
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0755, true);
    }
    
    $filename = $docType . '_' . $cert['id'] . '_' . time() . '.pdf';
    $filePath = $uploadDir . $filename;
    $pdf->Output('F', $filePath);
    
    $generatedPaths[$docType] = '/uploads/certificates/' . $filename;
}

// Update certificate record with paths + pattern_id + approved status
$db->update('certificates', [
    'certificate_pdf_path' => $generatedPaths['certificate'] ?? null,
    'marksheet_pdf_path'   => $generatedPaths['marksheet'] ?? null,
    'pattern_id'           => $patternId,
    'status'               => 'approved',
    'approved_at'          => date('Y-m-d H:i:s'),
    'approved_by'          => $_SESSION['user_id'] ?? null
], ['id' => $cert['id']]);
=============================================================================
*/
