<?php
require_once(__DIR__ . '/../Birth-Web/tcpdf/tcpdf.php');
include('../includes/config.php');
if (!isset($_SESSION['loggedin'])) { header("Location: ../index"); exit; }

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

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

$row = mysqli_fetch_assoc($result);

$name = $row['name'];
$gender = $row['gender'];
$dob = $row['date_of_birth'];
$place_of_birth = $row['place_of_birth'];
$date_of_registration = $row['date_of_registration'];
$registration_no = $row['registration_no'];
if (preg_match('/^MCDOLIR-(\d+)-(\d+)$/', $registration_no, $m)) {
    $registration_no = 'MCDOLIR-' . str_pad($m[1], 4, '0', STR_PAD_LEFT) . '-' . str_pad($m[2], 11, '0', STR_PAD_LEFT);
}
$mother_name = $row['mother_name'];
$father_name = $row['father_name'];
$present_address = $row['present_address'];
$permanent_address = $row['permanent_address'];
$date_of_issue = $row['date_of_issue'];

$imgDir = __DIR__ . '/../assets/images/';
$imgDirAlt = __DIR__ . '/delhi_assets/';
$hindiDir = $imgDir . 'hindi/';
// Use main assets folder first, fallback to delhi_assets

function getHindiImg($filename) {
    global $hindiDir, $imgDirAlt;
    $paths = [
        $hindiDir . $filename,
        $imgDirAlt . $filename,
        __DIR__ . '/../Birth-Web/assets/images/hindi/' . $filename
    ];
    foreach($paths as $path) {
        if(file_exists($path)) return $path;
    }
    return false;
}

function placeHindiImageCentered(&$pdf, $imgFile, $areaX, $areaY, $areaW, $targetH) {
    if (!$imgFile) return false;
    $info = @getimagesize($imgFile);
    if (!$info) return false;
    $imgW = $info[0]; $imgH = $info[1];
    $displayH = $targetH;
    $displayW = ($imgW / $imgH) * $displayH;
    if ($displayW > $areaW) { $displayW = $areaW; $displayH = ($imgH / $imgW) * $displayW; }
    $cx = $areaX + ($areaW - $displayW) / 2;
    $pdf->Image($imgFile, $cx, $areaY, $displayW, $displayH, 'PNG', '', '', false, 300);
    return true;
}

function placeHindiImageLeft(&$pdf, $imgFile, $x, $y, $maxW, $targetH) {
    if (!$imgFile) return false;
    $info = @getimagesize($imgFile);
    if (!$info) return false;
    $imgW = $info[0]; $imgH = $info[1];
    $displayH = $targetH;
    $displayW = ($imgW / $imgH) * $displayH;
    if ($displayW > $maxW) { $displayW = $maxW; $displayH = ($imgH / $imgW) * $displayW; }
    $pdf->Image($imgFile, $x, $y, $displayW, $displayH, 'PNG', '', '', false, 300);
    return true;
}

class MYPDF extends TCPDF {
    public $footerHindiImg = '';
    public function Header() {}
    public function Footer() {
        $this->SetY(-19);
        if ($this->footerHindiImg && file_exists($this->footerHindiImg)) {
            $info = @getimagesize($this->footerHindiImg);
            if ($info) {
                $dh = 5; $dw = ($info[0] / $info[1]) * $dh;
                $cx = (210 - $dw) / 2;
                $this->Image($this->footerHindiImg, $cx, $this->GetY(), $dw, $dh, 'PNG');
                $this->SetY($this->GetY() + $dh);
            }
        } else {
            $this->SetFont('freesans', 'B', 12);
            $this->SetTextColor(0, 0, 0);
            $this->Cell(0, 5, 'प्रत्येक जन्म एवं मृत्यु का पंजीकरण सुनिश्चित करे', 0, 1, 'C');
        }
        $this->SetFont('times', 'B', 11);
        $this->SetTextColor(0, 0, 0);
        $this->Cell(0, 5, 'ENSURE REGISTRATION OF EVERY BIRTH & DEATH', 0, 0, 'C');
    }
}

$pdf = new MYPDF('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(true);
$pdf->SetMargins(15, 15, 15);
$pdf->SetAutoPageBreak(TRUE, 22);
$pdf->footerHindiImg = getHindiImg('footer_hindi.png');
$pdf->AddPage();

$pageW = 210; $pageH = 297;
$marginL = 15; $marginR = 15;
$contentW = $pageW - $marginL - $marginR;

// Blue border
$pdf->SetDrawColor(0, 0, 139);
$pdf->SetLineWidth(1.5);
$borderMargin = 7;
$pdf->Rect($borderMargin, $borderMargin, $pageW - 2 * $borderMargin, $pageH - 2 * $borderMargin);

// Watermark
$mcdLogo = '';
$mcdWatermark = '';

$logoPaths = [
    $imgDir . 'mcd_logo.png',
    $imgDirAlt . 'mcd_logo.png'
];
foreach($logoPaths as $path) {
    if(file_exists($path)) { $mcdLogo = $path; break; }
}

$watermarkPaths = [
    $imgDir . 'mcd_watermark.png', 
    $imgDirAlt . 'mcd_watermark.png'
];
foreach($watermarkPaths as $path) {
    if(file_exists($path)) { $mcdWatermark = $path; break; }
}

if ($mcdWatermark) {
    $pdf->SetAlpha(0.08);
    $pdf->Image($mcdWatermark, 42, 88, 126, 126, '', '', '', false, 300);
    $pdf->SetAlpha(1);
} elseif ($mcdLogo) {
    $pdf->SetAlpha(0.08);
    $pdf->Image($mcdLogo, 42, 88, 126, 126, '', '', '', false, 300);
    $pdf->SetAlpha(1);
}

// MCD Logo (Left)
$logoY = 13;
if ($mcdLogo) {
    $pdf->Image($mcdLogo, $marginL, $logoY, 35, 35, '', '', '', false, 300);
}

// Ashoka Emblem (Center)
$ashokaImg = '';
$ashokaImages = [
    $imgDir . 'ashoka_emblem.png',
    $imgDirAlt . 'ashoka_emblem.png'
];
foreach($ashokaImages as $path) {
    if(file_exists($path)) { $ashokaImg = $path; break; }
}

if ($ashokaImg) {
    $pdf->Image($ashokaImg, 97, $logoY - 1, 15, 18, '', '', '', false, 300);
}

// Delhi Symbol (Right)
$delhiLogoX = 163; $delhiLogoY = $logoY - 2; $delhiLogoW = 30; $delhiLogoH = 32;
$delhiLogoFile = '';

$delhiLogoPaths = [
    $imgDir . 'state1.png',
    $imgDir . 'delhi_logo.png',
    $imgDirAlt . 'state1.png',
    $imgDirAlt . 'delhi_logo.png'
];
foreach($delhiLogoPaths as $path) {
    if(file_exists($path)) { $delhiLogoFile = $path; break; }
}

if ($delhiLogoFile) {
    $pdf->Image($delhiLogoFile, $delhiLogoX, $delhiLogoY, $delhiLogoW, $delhiLogoH, '', '', '', false, 300);
}

// Certificate number (below Delhi symbol)
$certificate_no = preg_replace('/^MCDOLIR-/', '', $registration_no);
$pdf->SetFont('times', 'B', 10);
$pdf->SetTextColor(0, 0, 0);
$regNoWidth = $pdf->GetStringWidth($certificate_no) + 4;
$regNoX = $delhiLogoX + ($delhiLogoW / 2) - ($regNoWidth / 2);
$pdf->SetXY($regNoX, $delhiLogoY + $delhiLogoH + 2);
$pdf->Cell($regNoWidth, 4, $certificate_no, 0, 1, 'C');

// Header text (Center) - Use professional header image if available
$hx = 55; $hw = 104;

$headerTextPath = '';
$headerPaths = [
    $imgDir . 'header_text.png',
    $imgDirAlt . 'header_text.png'
];
foreach($headerPaths as $path) {
    if(file_exists($path)) { $headerTextPath = $path; break; }
}

if($headerTextPath) {
    // Use professional header image - matches certifiicate.in exactly
    $pdf->Image($headerTextPath, $hx - 10, $logoY + 15, $hw + 20, 35, 'PNG', '', '', false, 300);
} else {
    // Fallback to individual image/text rendering
    $formNoImg = getHindiImg('form_no.png');
    if (!placeHindiImageCentered($pdf, $formNoImg, $hx, $logoY + 18, $hw, 4)) {
        $pdf->SetFont('freesans', '', 8); $pdf->SetTextColor(0, 0, 0);
        $pdf->SetXY($hx, $logoY + 18); $pdf->Cell($hw, 4, 'फॉर्म संख्या / Form No. 5', 0, 1, 'C');
    }

    $rashImg = getHindiImg('rashtiya.png');
    if (!placeHindiImageCentered($pdf, $rashImg, $hx, $logoY + 22, $hw, 5)) {
        $pdf->SetFont('freesans', 'B', 9); $pdf->SetTextColor(0, 0, 139);
        $pdf->SetXY($hx, $logoY + 22); $pdf->Cell($hw, 5, 'राष्ट्रीय राजधानी क्षेत्र, दिल्ली सरकार', 0, 1, 'C');
    }

    $pdf->SetFont('times', 'B', 10); $pdf->SetTextColor(0, 0, 0);
    $pdf->SetXY($hx, $logoY + 27); $pdf->Cell($hw, 5, 'Govt. of National Capital Territory of Delhi', 0, 1, 'C');

    $delhiImg = getHindiImg('delhi_nagar.png');
    if (!placeHindiImageCentered($pdf, $delhiImg, $hx, $logoY + 32, $hw, 7)) {
        $pdf->SetFont('freesans', 'B', 16); $pdf->SetTextColor(0, 0, 139);
        $pdf->SetXY($hx, $logoY + 32); $pdf->Cell($hw, 7, 'दिल्ली नगर निगम', 0, 1, 'C');
    }

    $pdf->SetFont('times', 'B', 11); $pdf->SetTextColor(0, 0, 0);
    $pdf->SetXY($hx, $logoY + 39); $pdf->Cell($hw, 5, 'MUNICIPAL CORPORATION OF DELHI', 0, 1, 'C');

    $birthImg = getHindiImg('birth_cert.png');
    if (!placeHindiImageCentered($pdf, $birthImg, $hx, $logoY + 44, $hw, 5)) {
        $pdf->SetFont('freesans', 'B', 10); $pdf->SetTextColor(0, 128, 0);
        $pdf->SetXY($hx, $logoY + 44); $pdf->Cell($hw, 5, 'जन्म प्रमाण पत्र / Birth Certificate', 0, 1, 'C');
    }
}

// Legal text
$legalY = $logoY + 51;
$pdf->SetY($legalY);
$pdf->SetFont('times', '', 9); $pdf->SetTextColor(0, 0, 0);
$pdf->SetX($marginL);
$pdf->MultiCell($contentW, 4.5, "(Issued under section 17 of the Registration of Birth and Death Act, 1969 and 8/13 of Delhi Registration of\nBirth Rule,1999)", 0, 'J');

$pdf->Ln(2);
$pdf->SetFont('times', '', 9);
$pdf->SetX($marginL);
$pdf->MultiCell($contentW, 4.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($place_of_birth) . " of N.C.T. Delhi", 0, 'J');

// Certificate details
$pdf->Ln(3);
$startY = $pdf->GetY();

$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'
);

$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'
);

$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))
);

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

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

for ($i = 0; $i < count($values); $i++) {
    $lblImg = getHindiImg($labelImages[$i]);
    $labelH = 5;
    if ($lblImg) {
        placeHindiImageLeft($pdf, $lblImg, $labelX, $y, $labelWidth, 5);
        $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
$qr_y = $y - 7;
$qrSize = 60;
$qrX = ($pageW - $qrSize) / 2;

$qr_data = "Birth Certificate - Municipal Corporation of Delhi\n";
$qr_data .= "Registration No: " . $registration_no . "\n";
$qr_data .= "Name: " . strtoupper($name) . "\n";
$qr_data .= "Gender: " . strtoupper($gender) . "\n"; 
$qr_data .= "Date of Birth: " . date('d/m/Y', strtotime($dob)) . "\n";
$qr_data .= "Father: " . strtoupper($father_name) . "\n";
$qr_data .= "Mother: " . strtoupper($mother_name) . "\n";
$qr_data .= "Place of Birth: " . strtoupper($place_of_birth) . "\n";
$qr_data .= "Date of Registration: " . date('d/m/Y', strtotime($date_of_registration)) . "\n";
$qr_data .= "Date of Issue: " . date('d/m/Y', strtotime($date_of_issue)) . "\n";
$qr_data .= "Issued by: Municipal Corporation of Delhi\n";
$qr_data .= "Verify online: 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');

// Note
$pdf->SetY($qr_y + $qrSize + 2);
$pdf->SetX($marginL);
$pdf->SetFont('times', 'B', 9); $pdf->SetTextColor(0, 0, 0);
$pdf->MultiCell($contentW, 4, "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, 'L');

// Output
$filename = 'Birth_Certificate_' . preg_replace('/[^A-Za-z0-9\-]/', '_', $name) . '.pdf';
$pdf->Output($filename, 'I');
