<?php
header('Content-Type: application/json');
header("Access-Control-Allow-Origin: *");

include_once '../config/database.php';
include_once '../models/Student.php';

// Include QR Code library
$qrLibPath = __DIR__ . '/phpqrcode/qrlib.php';
if (!file_exists($qrLibPath)) {
    // Fallback to API
    echo json_encode([
        "success" => true, 
        "qr_code_url" => "https://api.qrserver.com/v1/create-qr-code/?size=120x120&data=GATEWAY-ICT-POLY",
        "message" => "Using external QR service"
    ]);
    exit;
}

require_once $qrLibPath;

$database = new Database();
$db = $database->getConnection();

$student = new Student($db);
$student_id = $_POST['student_id'] ?? $_GET['student_id'] ?? null;

if (!$student_id) {
    echo json_encode(["success" => false, "message" => "Student ID is required"]);
    exit;
}

$student->id = $student_id;
$student->readOne();

if ($student->full_name != null) {
    // Create directories if they don't exist
    $qrDir = __DIR__ . '/../uploads/qrcodes/';
    if (!file_exists($qrDir)) {
        mkdir($qrDir, 0777, true);
    }
    
    // Get base URL for image paths
    $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http";
    $host = $_SERVER['HTTP_HOST'];
    $baseUrl = $protocol . "://" . $host . dirname($_SERVER['PHP_SELF']);
    $baseUrl = str_replace('/qr', '', $baseUrl);
    
    // Build photo URL
    $photoUrl = $student->photo_path;
    if ($student->photo_path && !filter_var($student->photo_path, FILTER_VALIDATE_URL)) {
        $photoUrl = $baseUrl . '/' . $student->photo_path;
    }
    

    // QR Code content with ALL student data including image URL
    $qrContent = "GATEWAY ICT POLYTECHNIC SAAPADE\n";
    $qrContent .= "================================\n";
    $qrContent .= "STUDENT ID: " . $student->student_id . "\n";
    $qrContent .= "FULL NAME: " . $student->full_name . "\n";
    $qrContent .= "PROGRAM: " . $student->program . "\n";
    $qrContent .= "DEPARTMENT: " . $student->department . "\n";
    $qrContent .= "GRADE: " . $student->grade . "\n";
    $qrContent .= "CERTIFICATE TYPE: " . ($student->certificate_type ?: 'National Diploma') . "\n";
    $qrContent .= "GRADUATION DATE: " . $student->graduation_date . "\n";
    $qrContent .= "CERTIFICATE ID: " . ($student->certificate_id ?: 'GICT-' . $student->id) . "\n";
    // $qrContent .= "PHOTO URL: " . $photoUrl . "\n";
    // $qrContent .= "==============================\n";
    //$qrContent .= "Verify: " . $baseUrl . "/verify.php?id=" . ($student->certificate_id ?: $student->id);

    
    // Generate certificate ID if not exists
    if (!$student->certificate_id) {
        $certificate_id = 'GICT-' . strtoupper(substr(str_replace(' ', '', $student->program), 0, 3)) . '-' . date('Y') . '-' . sprintf('%04d', $student->id);
        
        // Update student record with certificate ID
        $updateQuery = "UPDATE students SET certificate_id = ? WHERE id = ?";
        $stmt = $db->prepare($updateQuery);
        $stmt->execute([$certificate_id, $student->id]);
        
        $student->certificate_id = $certificate_id;
    }
    
    $qrCodePath = 'uploads/qrcodes/' . $student->certificate_id . '.png';
    $fullQrPath = __DIR__ . '/../' . $qrCodePath;
    
    try {
        // Generate QR Code with high error correction
        QRcode::png($qrContent, $fullQrPath, 'H', 6, 2);
        
        if (file_exists($fullQrPath)) {
            echo json_encode([
                "success" => true,
                "qr_code_path" => $qrCodePath,
                "certificate_id" => $student->certificate_id,
                "qr_content" => $qrContent,
                "photo_url" => $photoUrl,
                "message" => "QR Code generated successfully with complete student data including photo"
            ]);
        } else {
            // Fallback to API with all data
            $qrContentEncoded = urlencode($qrContent);
            echo json_encode([
                "success" => true,
                "qr_code_url" => "https://api.qrserver.com/v1/create-qr-code/?size=120x120&data=" . $qrContentEncoded,
                "certificate_id" => $student->certificate_id,
                "photo_url" => $photoUrl,
                "message" => "QR Code generated via API with complete student data including photo"
            ]);
        }
    } catch (Exception $e) {
        // Fallback to API with all data
        $qrContentEncoded = urlencode($qrContent);
        echo json_encode([
            "success" => true,
            "qr_code_url" => "https://api.qrserver.com/v1/create-qr-code/?size=120x120&data=" . $qrContentEncoded,
            "certificate_id" => $student->certificate_id,
            "photo_url" => $photoUrl,
            "message" => "QR Code generated via API with complete student data including photo"
        ]);
    }
} else {
    echo json_encode(["success" => false, "message" => "Student not found"]);
}
?>