<?php
require_once('tcpdf/tcpdf.php');
include "db.php";

$reg_no = isset($_GET['reg_no']) ? $_GET['reg_no'] : '';
if(empty($reg_no)) die("Registration number required");

$sql = "SELECT * FROM birth_certificate WHERE registration_no='$reg_no'";
$result = mysqli_query($conn, $sql);
if(mysqli_num_rows($result) == 0) die("Record not found");

$row = mysqli_fetch_assoc($result);

// Handle both column naming conventions
$name = isset($row['name']) ? $row['name'] : (isset($row['child_name']) ? $row['child_name'] : '');
$gender = $row['gender'];
$dob = isset($row['date_of_birth']) ? $row['date_of_birth'] : (isset($row['dob']) ? $row['dob'] : '');
$place_of_birth = $row['place_of_birth'];
$date_of_registration = isset($row['date_of_registration']) ? $row['date_of_registration'] : date('Y-m-d');
$registration_no = $row['registration_no'];
$mother_name = $row['mother_name'];
$father_name = $row['father_name'];
$present_address = isset($row['present_address']) ? $row['present_address'] : (isset($row['address']) ? $row['address'] : '');
$permanent_address = isset($row['permanent_address']) ? $row['permanent_address'] : (isset($row['address']) ? $row['address'] : '');
$date_of_issue = isset($row['date_of_issue']) ? $row['date_of_issue'] : (isset($row['issue_date']) ? $row['issue_date'] : date('Y-m-d H:i:s'));
$name_of_zone = isset($row['name_of_zone']) ? $row['name_of_zone'] : '';

// Always use registration_no and remove MCDOLIR- prefix for display
$display_reg = str_replace('MCDOLIR-', '', $registration_no);

// Prepare filename with child's name
$childName = !empty($name) ? strtoupper(trim($name)) : 'Certificate';
$childName = preg_replace('/[^A-Za-z0-9\s\-]/', '', $childName);
$childName = trim(preg_replace('/\s+/', ' ', $childName)); // Keep spaces, normalize multiple spaces to single
$filename = $childName . '.pdf';

// ============ HINDI IMAGE HELPER ============
function hindiImg($pdf, $file, $x, $y, $h, $areaW = 0, $align = 'L') {
    $path = 'assets/images/hindi/' . $file;
    if (!file_exists($path)) return false;
    $info = @getimagesize($path);
    if (!$info || $info[1] == 0) return false;
    $w = ($info[0] / $info[1]) * $h;
    if ($align === 'C' && $areaW > 0) {
        $x = $x + ($areaW - $w) / 2;
    }
    $pdf->Image($path, $x, $y, $w, $h, 'PNG', '', '', false, 300);
    return true;
}

// Create PDF
$pdf = new TCPDF('P', 'mm', 'A4', true, 'UTF-8', false);
$pdf->SetCreator('MCD Birth Certificate Portal');
$pdf->SetAuthor('Municipal Corporation of Delhi');
$pdf->SetTitle('Birth Certificate - ' . $name);
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);
$pdf->SetMargins(10, 10, 10);
$pdf->SetAutoPageBreak(false);

$pdf->AddPage();

// Page dimensions
$pageW = 210;
$pageH = 297;

// ============ BLUE BORDER (matching view: 8px solid #00008B) ============
$borderX = 4.5;
$borderY = 4.5;
$borderW = $pageW - 2 * $borderX;
$borderH = $pageH - 2 * $borderY;
$pdf->SetDrawColor(0, 0, 139); // #00008B
$pdf->SetLineWidth(2.8);
$pdf->Rect($borderX, $borderY, $borderW, $borderH);

// Content area (inside border + inner padding matching view: 6mm top, 7mm sides)
$contentL = $borderX + 1.4 + 7;   // ~12.9mm
$contentR = $pageW - $borderX - 1.4 - 7; // ~197.1mm
$contentT = $borderY + 1.4 + 6;   // ~11.9mm
$contentW = $contentR - $contentL; // ~184.2mm

// ============ WATERMARK (matching view: 500px centered, opacity 0.10) ============
$wmFile = '';
if(file_exists('assets/images/mcd_watermark.png')) $wmFile = 'assets/images/mcd_watermark.png';
elseif(file_exists('assets/images/mcd_logo.png')) $wmFile = 'assets/images/mcd_logo.png';
if($wmFile){
    $wmSize = 132; // 500px ≈ 132mm
    $pdf->SetAlpha(0.10);
    $pdf->Image($wmFile, ($pageW - $wmSize)/2, ($pageH - $wmSize)/2, $wmSize, $wmSize, '', '', '', false, 300);
    $pdf->SetAlpha(1);
}

// ============ HEADER LAYOUT (matching view flexbox) ============
// View: logo-left 100px wide, logo-right 100px wide, center flex:1
$logoColW = 32;
$headerCenterL = $contentL + $logoColW;
$headerCenterW = $contentW - $logoColW - $logoColW;

// --- MCD Logo - Left (view: 120x120px ≈ 30mm, padding-top: 35px ≈ 9mm) ---
$mcdLogoSize = 30;
$mcdLogoX = $contentL;
$mcdLogoY = $contentT + 9;
if(file_exists('assets/images/mcd_logo.png')){
    $pdf->Image('assets/images/mcd_logo.png', $mcdLogoX, $mcdLogoY, $mcdLogoSize, $mcdLogoSize, '', '', '', false, 300);
}

// --- Ashoka Emblem - Center top (view: 70x78px ≈ 18x20mm) ---
$ashokaW = 18;
$ashokaH = 20;
$ashokaX = $headerCenterL + ($headerCenterW - $ashokaW) / 2;
$ashokaY = $contentT - 1;
if(file_exists('assets/images/ashoka_emblem.png')){
    $pdf->Image('assets/images/ashoka_emblem.png', $ashokaX, $ashokaY, $ashokaW, $ashokaH, '', '', '', false, 300);
}

// --- Delhi Logo - Right (view: 115x140px ≈ 28x34mm, padding-top: 38px ≈ 10mm) ---
$delhiLogoW = 28;
$delhiLogoH = 34;
$delhiLogoX = $contentR - $delhiLogoW;
$delhiLogoY = $contentT + 10;
$delhiLogoFile = '';
if(file_exists('assets/images/state1.png')) $delhiLogoFile = 'assets/images/state1.png';
elseif(file_exists('assets/images/delhi_logo.png')) $delhiLogoFile = 'assets/images/delhi_logo.png';
if($delhiLogoFile){
    $pdf->Image($delhiLogoFile, $delhiLogoX, $delhiLogoY, $delhiLogoW, $delhiLogoH, '', '', '', false, 300);
}

// --- Certificate Number below Delhi logo (view: 13px bold, centered) ---
$pdf->SetFont('times', 'B', 10);
$pdf->SetTextColor(0, 0, 0);
$regNoWidth = $pdf->GetStringWidth($display_reg) + 4;
$regNoX = $delhiLogoX + ($delhiLogoW / 2) - ($regNoWidth / 2);
$pdf->SetXY($regNoX, $delhiLogoY + $delhiLogoH + 1);
$pdf->Cell($regNoWidth, 4, $display_reg, 0, 1, 'C');

// ============ HEADER TEXT (center column) ============
$hx = $headerCenterL;
$hw = $headerCenterW;
$textStartY = $ashokaY + $ashokaH + 1;

// Use header_text.png image if it exists (matching view_certificate.php exactly)
if(file_exists('assets/images/header_text.png')) {
    // Single pre-made header image with all text perfectly formatted
    $headerImgW = 110; // width in mm
    $headerImgH = 55;  // height in mm
    $headerImgX = $hx + ($hw - $headerImgW) / 2;
    $pdf->Image('assets/images/header_text.png', $headerImgX, $textStartY, $headerImgW, $headerImgH, 'PNG', '', '', false, 300);
    $y6 = $textStartY + $headerImgH;
} else {
    // Fallback: render text individually
    // फॉर्म संख्या / Form No. 5
    if(!hindiImg($pdf, 'form_no.png', $hx, $textStartY, 3.5, $hw, 'C')) {
        $pdf->SetFont('dejavusans', '', 10);
        $pdf->SetTextColor(51, 51, 51);
        $pdf->SetXY($hx, $textStartY);
        $pdf->Cell($hw, 4, 'फॉर्म संख्या / Form No. 5', 0, 1, 'C');
    }
    
    $y2 = $textStartY + 5;
    // राष्ट्रीय राजधानी क्षेत्र, दिल्ली सरकार
    if(!hindiImg($pdf, 'rashtiya.png', $hx, $y2, 5, $hw, 'C')) {
        $pdf->SetFont('dejavusans', 'B', 13);
        $pdf->SetTextColor(26, 10, 110);
        $pdf->SetXY($hx, $y2);
        $pdf->Cell($hw, 5, 'राष्ट्रीय राजधानी क्षेत्र, दिल्ली सरकार', 0, 1, 'C');
    }
    
    $y3 = $y2 + 6;
    // Govt. of National Capital Territory of Delhi
    $pdf->SetFont('times', 'BI', 14);
    $pdf->SetTextColor(26, 10, 110);
    $pdf->SetXY($hx, $y3);
    $pdf->Cell($hw, 5, 'Govt. of National Capital Territory of Delhi', 0, 1, 'C');
    
    $y4 = $y3 + 7;
    // दिल्ली नगर निगम
    if(!hindiImg($pdf, 'delhi_nagar.png', $hx, $y4, 9, $hw, 'C')) {
        $pdf->SetFont('dejavusans', 'B', 22);
        $pdf->SetTextColor(13, 107, 61);
        $pdf->SetXY($hx, $y4);
        $pdf->Cell($hw, 9, 'दिल्ली नगर निगम', 0, 1, 'C');
    }
    
    $y5 = $y4 + 10;
    // MUNICIPAL CORPORATION OF DELHI
    $pdf->SetFont('times', 'B', 14);
    $pdf->SetTextColor(26, 10, 110);
    $pdf->SetXY($hx, $y5);
    $pdf->Cell($hw, 5, 'MUNICIPAL CORPORATION OF DELHI', 0, 1, 'C');
    
    $y6 = $y5 + 6;
    // जन्म प्रमाण पत्र / Birth Certificate
    if(!hindiImg($pdf, 'birth_cert.png', $hx, $y6, 5, $hw, 'C')) {
        $pdf->SetFont('dejavusans', 'BI', 12);
        $pdf->SetTextColor(13, 107, 61);
        $pdf->SetXY($hx, $y6);
        $pdf->Cell($hw, 5, 'जन्म प्रमाण पत्र / Birth Certificate', 0, 1, 'C');
    }
    $y6 = $y6 + 6;
}

// ============ LEGAL TEXT (matching view: 15.5px, bold, left-aligned) ============
$legalY = $y6 + 2;
$pdf->SetY($legalY);
$pdf->SetFont('times', 'B', 11);
$pdf->SetTextColor(0, 0, 0);
$pdf->SetX($contentL);
$pdf->MultiCell($contentW, 5, "(Issued under section 17 of the Registration of Birth and Death Act, 1969 and 8/13 of Delhi Registration of Birth Rule,1999)", 0, 'L');

$pdf->Ln(2);
$pdf->SetFont('times', 'B', 11);
$pdf->SetX($contentL);
$pdf->MultiCell($contentW, 5, "This is to certify that the following information has been taken from the original record of BIRTH which is the register for Municipal Corporation Of Delhi of " . strtoupper($name_of_zone) . " of N.C.T. Delhi", 0, 'L');

// ============ CERTIFICATE DETAILS TABLE ============
$pdf->Ln(2);
$startY = $pdf->GetY();

// Labels — matching crs/dehli_birth_pdf.php exactly
$labelTexts = array(
    'नाम / Name',
    'लिंग / Gender',
    'जन्म की तिथि / Date Of Birth',
    'जन्म का स्थान / Place Of Birth',
    'पंजीकरण की तिथि / Date Of Registration',
    'पंजीकरण संख्या / Registration No',
    'माता का नाम / Name of Mother',
    'पिता का नाम / Name of Father',
    'वर्तमान पता / Present Address',
    'स्थाई पता / Permanent Address',
    'जारी करने की तिथि / Date of Issue'
);

$labelImages = array(
    'label_name.png', 'label_gender.png', 'label_dob.png',
    'label_pob.png', 'label_dor.png', 'label_reg.png',
    'label_mother.png', 'label_father.png', 'label_present.png',
    'label_permanent.png', 'label_doi.png'
);

$values = array(
    strtoupper($name),
    strtoupper($gender),
    date('d/m/Y', strtotime($dob)),
    strtoupper($place_of_birth),
    date('d/m/Y', strtotime($date_of_registration)),
    $registration_no,
    strtoupper($mother_name),
    strtoupper($father_name),
    strtoupper($present_address),
    strtoupper($permanent_address),
    date('d/m/Y', strtotime($date_of_issue))
);

// Layout matching crs PDF structure
$bottomReserved = 70;
$availableForDetails = $pageH - $startY - $bottomReserved;
$rowHeight = $availableForDetails / count($values);
if ($rowHeight < 6) $rowHeight = 6;
if ($rowHeight > 10) $rowHeight = 10;

$y = $startY;
$labelX = $contentL;
$labelWidth = 70;
$valueX = $labelX + $labelWidth + 2;
$valueWidth = $contentW - $labelWidth - 2;

for ($i = 0; $i < count($values); $i++) {
    $lblImg = 'assets/images/hindi/' . $labelImages[$i];
    $labelH = 5;
    
    if (file_exists($lblImg)) {
        hindiImg($pdf, $labelImages[$i], $labelX, $y, 5, $labelWidth, 'L');
        $labelH = 5;
    } else {
        $pdf->SetXY($labelX, $y);
        $pdf->SetFont('freesans', '', 10); 
        $pdf->SetTextColor(0, 0, 0);
        $pdf->MultiCell($labelWidth, 5, $labelTexts[$i], 0, 'L');
        $labelH = $pdf->getLastH();
    }

    $pdf->SetXY($valueX, $y);
    $pdf->SetFont('times', '', 10); 
    $pdf->SetTextColor(0, 0, 0);
    $pdf->MultiCell($valueWidth, 5, $values[$i], 0, 'L');
    $valueH = $pdf->getLastH();

    $actualRowH = max($labelH, $valueH);
    $gap = $rowHeight - $actualRowH;
    if ($gap < 0.5) $gap = 0.5;
    $y += $actualRowH + $gap;
}

// ============ QR CODE (matching crs: 60x60mm, centered) ============
$qrSize = 60;
$qrX = ($pageW - $qrSize) / 2;
$qr_y = $y - 7;

$qr_data = "Registration No: " . $registration_no . "\n";
$qr_data .= "Name: " . strtoupper($name) . "\n";
$qr_data .= "Gender: " . strtoupper($gender) . "\n";
$qr_data .= "DOB: " . date('d/m/Y', strtotime($dob)) . "\n";
$qr_data .= "Father: " . strtoupper($father_name) . "\n";
$qr_data .= "Mother: " . strtoupper($mother_name) . "\n";
$qr_data .= "Place: " . strtoupper($place_of_birth) . "\n";
$qr_data .= "Zone: " . strtoupper($name_of_zone) . "\n";
$qr_data .= "Verify: https://mcdonline.nic.in/verify?reg=" . urlencode($registration_no);

$style = array(
    'border' => 0,
    'vpadding' => 'auto',
    'hpadding' => 'auto',
    'fgcolor' => array(0, 0, 0),
    'bgcolor' => false,
    'module_width' => 1,
    'module_height' => 1
);

$pdf->write2DBarcode($qr_data, 'QRCODE,M', $qrX, $qr_y, $qrSize, $qrSize, $style, 'N');

// ============ FOOTER (matching view: 12px, bold, centered) ============
$footerY = $qr_y + $qrSize + 2;

// Hindi footer
if(!hindiImg($pdf, 'footer_hindi.png', 0, $footerY, 4, $pageW, 'C')) {
    $pdf->SetXY(0, $footerY);
    $pdf->SetFont('dejavusans', 'B', 9);
    $pdf->SetTextColor(0, 0, 0);
    $pdf->Cell($pageW, 4, 'प्रत्येक जन्म एवं मृत्यु का पंजीकरण सुनिश्चित करें', 0, 0, 'C');
}

// English footer
$pdf->SetXY(0, $footerY + 5);
$pdf->SetFont('times', 'B', 9);
$pdf->SetTextColor(0, 0, 0);
$pdf->Cell($pageW, 4, 'ENSURE REGISTRATION OF EVERY BIRTH & DEATH', 0, 0, 'C');

// ============ NOTE (matching view: 13px, bold, centered) ============
$noteY = $footerY + 11;
$pdf->SetXY($contentL, $noteY);
$pdf->SetFont('times', 'B', 9);
$pdf->SetTextColor(0, 0, 0);
$pdf->MultiCell($contentW, 3.5, "Note: This certificate is system generated and does not require any seal/signature in original. The authenticity of this certificate can be verified at mcdonline.nic.in", 0, 'C');

// Output PDF with proper headers
// Clear any previous output
@ob_end_clean();

// Set headers to force download with correct filename
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');

// Output PDF
$pdf->Output($filename, 'D');
