<?php
ob_start();
session_start();
chdir('../');
require_once('assets/vendor/tcpdf/tcpdf.php');
require_once("public/connection.php");
require_once("public/functions.php");

// Watermark, Header and Footer
class MYPDF extends TCPDF {
    protected $logo_path = '';
    protected $school_name = '';
    protected $school_website = '';
    protected $school_phone = '';

    public function setWatermarkImage($path) {
        $this->logo_path = $path;
    }

    public function setFooterDetails($name, $website, $phone) {
        $this->school_name = $name;
        $this->school_website = $website;
        $this->school_phone = $phone;
    }

    public function Header() {
        if (!empty($this->logo_path)) {
            $this->SetAlpha(0.08);
            $this->Image($this->logo_path, 35, 80, 140, 140, '', '', '', false, 300, '', false, false, 0);
            $this->SetAlpha(1);
        }
    }

	public function Footer() {
		$this->SetY(-20); // Position 20mm from bottom
		$this->SetFont('helvetica', 'I', 8);

		// Black color for general footer
		$this->SetTextColor(0, 0, 0);

		// Page number and school contact
		$pageNum = 'Page ' . $this->getAliasNumPage() . '/' . $this->getAliasNbPages();
		$printDate = 'Printed on: ' . date('Y-m-d');
		$contact = $this->school_name . ' | ' . $this->school_website . ' | ' . $this->school_phone;
		$this->Cell(0, 5, $pageNum . ' | ' . $printDate . ' | ' . $contact, 0, 1, 'C');

		// 🔴 Red text for notice
		$this->SetTextColor(255, 0, 0);
		$notice = "This is an official document of {$this->school_name}. Unauthorized reproduction is prohibited.";
		$this->Cell(0, 5, $notice, 0, 1, 'C');

		// 🔵 Blue bold text for credit
		$this->SetTextColor(0, 0, 255);
		$this->SetFont('helvetica', 'B', 8);
		$this->Cell(0, 5, 'Powered by Syntax Digital Technology Ltd, 08165684612', 0, 0, 'C');
	}

}



// Validate GET ID
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    ob_end_clean();
    die("Invalid or missing student ID.");
}
$student_id = (int)$_GET['id'];

// Fetch student info
$query = "SELECT * FROM students WHERE id = '$student_id'";
$run_query = mysqli_query($connection, $query);
if (mysqli_num_rows($run_query) != 1) {
    ob_end_clean();
    die("Student not found.");
}
$student = mysqli_fetch_assoc($run_query);

// Extract student data
$surname = ucfirst($student['firstname']);
$lastname = ucfirst($student['lastname']);
$othername = ucfirst($student['othername']);
$fullname = "$surname $othername $lastname";
$reg_number = $student['reg_number'];
$student_class = $student['class'];
$level = $student['level'];
$gender = ucfirst($student['gender']);
$dob = $student['dob'];
$height = $student['height'];
$weight = $student['weight'];
$club = $student['club'];
$health_conditions = $student['health_conditions'];
$address = ucwords($student['address']);
$state = ucwords($student['state']);
$lga = ucwords($student['lga']);
$nationality = ucwords($student['nationality']);
$guardian_name = $student['guardian_name'];
$guardian_phone = $student['guardian_phone'];
$guardian_occupation = $student['guardian_occupation'];
$passport = !empty($student['passport']) ? './' . $student['passport'] : './uploads/students/none.jpg';
$date_of_reg = $student['date_of_reg'];

// Calculate age
$dob_object = DateTime::createFromFormat('d/m/Y', $dob);
$today = new DateTime();
if ($dob_object && $dob_object->format('d/m/Y') === $dob) {
    $age_diff = $dob_object->diff($today);
    $student_age = $age_diff->y . " year" . ($age_diff->y != 1 ? "s" : "") . ", " .
                   $age_diff->m . " month" . ($age_diff->m != 1 ? "s" : "") . ", " .
                   $age_diff->d . " day" . ($age_diff->d != 1 ? "s" : "");
} else {
    $student_age = "Invalid DOB";
}

// Fetch school info
$query = "SELECT * FROM administratives LIMIT 1";
$school_result = mysqli_query($connection, $query);
$school = mysqli_fetch_assoc($school_result);
$school_logo = './' . $school['school_logo'];  // Logo path relative to this file
$school_name = $school['school_name'];
$school_address = $school['school_address'];
$school_motto = $school['school_motto'];
$school_phone = $school['school_phone'];
$school_website = $school['school_website'];

// Start TCPDF
$pdf = new MYPDF('P', 'mm', 'A4', true, 'UTF-8', false);
$pdf->setWatermarkImage($school_logo);
$pdf->setFooterDetails($school_name, $school_website, $school_phone);
$pdf->SetTitle($reg_number);
$pdf->SetMargins(10, 10, 10);
$pdf->AddPage();

// === Updated Header with Left Logo, Center Text, Right Passport === //

// === Header: Left Logo, Center Text, Right Passport (Same Size, Higher Position) === //

$imgWidth = 30;
$imgHeight = 30;
$topY = 5;

// Left: School Logo
$pdf->Image($school_logo, 15, $topY, $imgWidth, $imgHeight, '', '', '', false, 300);

// Right: Student Passport (same size as logo)
$pdf->Image($passport, 165, $topY, $imgWidth, $imgHeight, '', '', '', false, 300);

// Centered header text
$pdf->SetY($topY + 5);  // Move up header text
$pdf->SetFont('helvetica', 'B', 14);
$pdf->Cell(0, 6, strtoupper($school_name), 0, 1, 'C');
$pdf->SetFont('helvetica', '', 10);
$pdf->Cell(0, 5, $school_motto, 0, 1, 'C');
$pdf->Cell(0, 5, $school_address, 0, 1, 'C');

// Optional separator line below header
$pdf->Ln(10);
$pdf->Ln(5);


// === Student Info (HTML Tables) === //
$html = <<<EOD
<h3>Student Bio-Data</h3>
<table cellpadding="5" border="1">
    <tr><td><b>Full Name:</b></td><td>{$fullname}</td></tr>
    <tr><td><b>Gender:</b></td><td>{$gender}</td></tr>
    <tr><td><b>Date of Birth:</b></td><td>{$dob}</td></tr>
    <tr><td><b>Age:</b></td><td>{$student_age}</td></tr>
    <tr><td><b>Height:</b></td><td>{$height} ft</td></tr>
    <tr><td><b>Weight:</b></td><td>{$weight} kg</td></tr>
    <tr><td><b>Health Conditions:</b></td><td>{$health_conditions}</td></tr>
</table>

<br/><h3>Academic Info</h3>
<table cellpadding="5" border="1">
    <tr><td><b>Reg Number:</b></td><td>{$reg_number}</td></tr>
    <tr><td><b>Class:</b></td><td>{$student_class}</td></tr>
    <tr><td><b>Level:</b></td><td>{$level}</td></tr>
    <tr><td><b>Club:</b></td><td>{$club}</td></tr>
    <tr><td><b>Date Registered:</b></td><td>{$date_of_reg}</td></tr>
</table>

<br/><h3>Contact & Address</h3>
<table cellpadding="5" border="1">
    <tr><td><b>Address:</b></td><td>{$address}</td></tr>
    <tr><td><b>LGA / State / Nationality:</b></td><td>{$lga}, {$state}, {$nationality}</td></tr>
</table>

<br/><h3>Guardian Details</h3>
<table cellpadding="5" border="1">
    <tr><td><b>Name:</b></td><td>{$guardian_name}</td></tr>
    <tr><td><b>Phone:</b></td><td>{$guardian_phone}</td></tr>
    <tr><td><b>Occupation:</b></td><td>{$guardian_occupation}</td></tr>
</table>
EOD;

// Output HTML
$pdf->writeHTML($html, true, false, true, false, '');

// ✅ Clean output buffer before sending PDF
if (headers_sent($file, $line)) {
    die("Headers already sent in $file on line $line");
}
while (ob_get_level()) {
    ob_end_clean();
}
$pdf->Output("Bio-Data.pdf", 'I');
exit;
?>

