<?php
include "../include/config.php";
session_start();
require('../fpdf/fpdf.php');

// Check if POST data exists
if(isset($_POST['pid'])){
    $intake = mysqli_real_escape_string($conn, $_POST['intake']);
    $program = mysqli_real_escape_string($conn, $_POST['program']);
} else {
    die("No POST data received");
}

$pdf = new FPDF();
$pdf->AddPage();

// Get school information
$sql = "SELECT * FROM admin WHERE limit 1";
$resultadmin = mysqli_query($conn, $sql);


$adminData = mysqli_fetch_assoc($resultadmin);
$slogo = $adminData['logo'];
$sname = strtoupper($adminData['sname']);
$sig = $adminData['sign'];
$stam1 = $adminData['stamp'];
$call = $adminData['contact'];
$add = $adminData['address'];
$web = $adminData['web'];

// Get students data
$sql = "SELECT `id`, `image`, `studentid`, `studentname`, `parent_name`, `parent_mobile`, 
               `parent_email`, `parent_relation`, `intake`, `gender`, `start_year`, `end_year`, 
               `program`, `mobile`, `email`, `pass`, `status`, `boarding_status`, `hostel_name`, 
               `room_number`, `exam`, `class`, `classsession` 
        FROM `students` 
        WHERE intake='$intake' AND program='$program'";

$result = mysqli_query($conn, $sql);

if(mysqli_num_rows($result) == 0) {
    die("No students found for the selected criteria");
}

$cardCount = 0;
$currentYear = date("Y");

while ($student = mysqli_fetch_array($result)) {
    if ($cardCount == 8) {
        $pdf->AddPage();
        $cardCount = 0;
    }
    
    $pdf->SetFont('Arial', '', 12);
    $exam = isset($student['exam']) ? $student['exam'] : 'N/A';
    $roll = $student['studentid'];
    $name = $student['studentname'];
    $session = $student['classsession'];
    $image = $student['image'];
    $gender = strtoupper($student['gender']);
    $image = strtok($image, '?');
    $clas = strtoupper($student['class']);
    
    // Fixed grade calculation
    if(isset($student['start_year'])) {
        $grade = ($currentYear - $student['start_year'] + 1) . $clas;
    } else {
        $grade = 'Unknown';
    }
    
    $column = $cardCount % 2; 
    $row = floor($cardCount / 2); 

    $xOffset = $column == 0 ? 8 : 110; 
    $yOffset = 66.9 * $row;

    // Background image
    $pdf->Image("images/download.jpg", $xOffset, $yOffset + 10, 95, 63);
    $pdf->Image("images/coat.png", $xOffset + 5, $yOffset + 12, 10, 0);
    $pdf->Image("../img/$slogo", $xOffset + 76, $yOffset + 9, 13, 13);

    // School information
    $pdf->SetXY($xOffset, $yOffset + 19);
    $pdf->SetFont('Arial', 'B', 10);
    $pdf->SetX($xOffset); 
    $pdf->Cell(95, 2, 'MINISTRY OF EDUCATION', 0, 1, 'C');
    $pdf->SetX($xOffset);
    $pdf->Cell(95, 9, $sname, 0, 1, 'C');
    $pdf->SetX($xOffset);
    $pdf->Cell(95, 3, 'PUPIL ID CARD', 0, 1, 'C');

    // Student photo area
    $pdf->SetFillColor(250, 250, 250);
    $pdf->Rect($xOffset + 9, $yOffset + 39.5, 25, 29, true);
    
    // Student image - with error handling
    if(file_exists($image)) {
        $pdf->Image($image, $xOffset + 11.5, $yOffset + 41, 20, 24);
    } else {
        $pdf->SetXY($xOffset + 11.5, $yOffset + 45);
        $pdf->SetFont('Arial', '', 6);
        $pdf->Cell(20, 5, 'No Photo', 0, 1, 'C');
    }

    // Student information
    $pdf->SetFont('Arial', '', 7.7);
    $pdf->SetXY($xOffset + 35, $yOffset + 37);
    $pdf->Cell(15, 10, 'NAME:', 0, 0);
    $pdf->Cell(40, 10, substr($name, 0, 20), 0, 1, 'L'); // Limit name length

    $pdf->SetXY($xOffset + 35, $yOffset + 40.5);
    $pdf->Cell(15, 10, 'EXAM No:', 0, 0);
    $pdf->Cell(20, 10, substr($exam, 0, 15), 0, 1, 'L');

    $pdf->SetXY($xOffset + 35, $yOffset + 43.5);
    $pdf->Cell(15, 10, 'ROLL:', 0, 0);
    $pdf->Cell(20, 10, substr($roll, 0, 15), 0, 1, 'L');

    $pdf->SetXY($xOffset + 35, $yOffset + 46.5);
    $pdf->Cell(15, 10, 'GRADE:', 0, 0);
    $pdf->Cell(20, 10, strtoupper($grade), 0, 1, 'L');

    $pdf->SetXY($xOffset + 35, $yOffset + 49.5);
    $pdf->Cell(15, 10, 'GENDER:', 0, 0);
    $pdf->Cell(20, 10, $gender, 0, 1, 'L');

    // Signature area
    $pdf->SetXY($xOffset + 35, $yOffset + 60);
    $pdf->Cell(40, 10, 'Headteacher Sign:', 0, 0);

    $pdf->Rect($xOffset + 80, $yOffset + 62, 10, 10, true);
    $pdf->Image("images/bar.png", $xOffset + 81, $yOffset + 63, 8, 8);

    // Footer information
    $pdf->SetXY($xOffset + 9.3, $yOffset + 65.3);
    $pdf->SetFont('Arial', 'B', 6);
    $expDate = date('d/m/Y', strtotime('+1 year'));
    $pdf->Cell(25, 10, "Exp Date: $expDate", 0, 0);
    $pdf->SetFont('Arial', 'B', 8);
    $pdf->Cell(60, 10, date('y/m').'-E', 0, 0, 'C');

    // School signature
    if(file_exists("../img/$sig")) {
        $pdf->Image("../img/$sig", $xOffset + 61, $yOffset + 58, 14, 7);
    }

    $cardCount++;
}

$pdf->Output('I', 'Student_ID_Cards.pdf'); // Output to browser
?>