<?php 
chdir('../');
ob_start();
session_start();
ini_set('display_errors', 1);
error_reporting(E_ALL);

require_once("public/connection.php");
require_once("public/functions.php");
require_once("assets/vendor/tcpdf/tcpdf.php");

define("K_TCPDF_EXTERNAL_IMAGES", true);

// ====================
// Amount to Words Function
function numberToWords($amount){
    $f = new NumberFormatter("en", NumberFormatter::SPELLOUT);
    $naira = floor($amount);
    $kobo = round(($amount - $naira) * 100);
    $words = ucfirst($f->format($naira)) . " Naira";
    if($kobo>0) $words .= " and ".$f->format($kobo)." Kobo";
    return $words." Only";
}

// ====================
// Get receipt
$receipt_id = isset($_GET['receipt_id']) ? (int)$_GET['receipt_id'] : 0;
if ($receipt_id <= 0) die("Invalid receipt ID.");

// ====================
// Fetch receipt info
$stmt = $connection->prepare("
    SELECT r.*, fp.family_id, fp.reg_number AS fp_reg_number, fp.custom_ref,
           f.family_name, f.discount_percent
    FROM fee_payment_receipts r
    LEFT JOIN fee_payment fp ON fp.id = r.fee_payment_id
    LEFT JOIN families f ON f.id = fp.family_id
    WHERE r.id = ?
    LIMIT 1
");
$stmt->bind_param("i", $receipt_id);
$stmt->execute();
$receipt_query = $stmt->get_result();
$stmt->close();
if (!$receipt_query || $receipt_query->num_rows === 0) die("Receipt not found.");
$receipt = $receipt_query->fetch_assoc();

// ====================
// Fetch school details
$school_query = $connection->query("
    SELECT school_name, school_motto, school_address, school_phone, school_website, school_logo
    FROM administratives LIMIT 1
");
if (!$school_query || $school_query->num_rows === 0) die("School details not found.");
$school = $school_query->fetch_assoc();

// ====================
// Logo
$logoHtml = '';
if (!empty($school['school_logo'])){
    $logoPath = dirname(__DIR__) . '/' . ltrim($school['school_logo'],'/');
    if (!file_exists($logoPath)) die("Logo file not found: ".$logoPath);
    $logoHtml = '<img src="'.$logoPath.'" style="height:55px;">'; // bigger logo
}

// ====================
// Setup PDF
$pdf = new TCPDF('P','mm','A4',true,'UTF-8',false);
$pdf->SetMargins(15,15,15);
$pdf->SetFont('helvetica','',10); // slightly smaller
$pdf->SetAutoPageBreak(TRUE,15);
$pdf->AddPage();

// ====================
$html = '<table width="100%" cellpadding="0" cellspacing="0">
<tr>
    <td style="text-align:center;">
        <!-- Centered Logo -->
        <img src="'.$logoPath.'" style="height:50px; margin-bottom:5px;"><br>

        <!-- School Details -->
        <h2 style="margin:0; padding:0; font-size:18px; line-height:20px;">'.htmlspecialchars($school['school_name'] ?? '').'</h2>
        <p style="margin:0; padding:0; font-size:12px; line-height:14px;">'.htmlspecialchars($school['school_motto'] ?? '').'</p>
        <p style="margin:0; padding:0; font-size:11px; line-height:13px;">'.htmlspecialchars($school['school_address'] ?? '').'</p>
        <p style="margin:0; padding:0; font-size:11px; line-height:13px;">Tel: '.htmlspecialchars($school['school_phone'] ?? '').' | '.htmlspecialchars($school['school_website'] ?? '').'</p>
    </td>
</tr>
</table>
<hr style="border:1px solid #000; margin-top:5px;">';
// ====================
// Initialize totals
$total_fee_all = $total_prev_paid_all = $total_paid_all = 0;
$students = [];

// ====================
// Fetch students and calculate payments
if(!empty($receipt['family_id'])){
    $stmt_stu = $connection->prepare("
        SELECT s.firstname, COALESCE(s.othername,'') AS othername, s.lastname, s.reg_number, s.class,
               fp.total_fee
        FROM students s
        LEFT JOIN fee_payment fp ON fp.reg_number=s.reg_number AND fp.family_id=s.family_id
        WHERE s.family_id=?
    ");
    $stmt_stu->bind_param("i",$receipt['family_id']);
    $stmt_stu->execute();
    $res_stu = $stmt_stu->get_result();
    $student_rows=[];
    while($stu=$res_stu->fetch_assoc()) $student_rows[]=$stu;
    $stmt_stu->close();

    $prev_total_query = $connection->query("
        SELECT SUM(amount_paid) AS total_prev
        FROM fee_payment_receipts
        WHERE fee_payment_id={$receipt['fee_payment_id']} AND id<{$receipt_id}
    ");
    $prev_total=floatval($prev_total_query->fetch_assoc()['total_prev']??0);

    $student_count=count($student_rows);
    $prev_per_student = $student_count? round($prev_total/$student_count,3):0;
    $prev_distributed_total=0;

    foreach($student_rows as $index=>$stu){
        $prev_paid = ($index===$student_count-1)? round($prev_total-$prev_distributed_total,3): $prev_per_student;
        if($index!=$student_count-1) $prev_distributed_total+=$prev_paid;
        $remaining=floatval($stu['total_fee']??0)-$prev_paid;
        $students[]=[
            'name'=>trim($stu['firstname'].' '.$stu['othername'].' '.$stu['lastname']),
            'reg'=>$stu['reg_number'],
            'class'=>$stu['class'],
            'total_fee'=>floatval($stu['total_fee']??0),
            'prev_paid'=>$prev_paid,
            'remaining'=>$remaining
        ];
    }

    $total_remaining=array_sum(array_column($students,'remaining'));
    $distributed_total=0;
    foreach($students as $index=>&$stu){
        $paid = ($total_remaining>0)? (($index===count($students)-1)? round(floatval($receipt['amount_paid'])-$distributed_total,3)
        : round(floatval($receipt['amount_paid'])*($stu['remaining']/$total_remaining),3)) :0;
        if($index!==count($students)-1) $distributed_total+=$paid;
        $stu['paid']=$paid;
        $stu['balance']=round(max(0,$stu['remaining']-$paid),3);
        $total_fee_all+=$stu['total_fee'];
        $total_prev_paid_all+=$stu['prev_paid'];
        $total_paid_all+=$stu['paid'];
    }
    unset($stu);

}else{
    $stmt_ind=$connection->prepare("
        SELECT s.firstname, COALESCE(s.othername,'') AS othername, s.lastname, s.class, fp.total_fee
        FROM students s
        LEFT JOIN fee_payment fp ON fp.reg_number=s.reg_number
        WHERE s.reg_number=?
        LIMIT 1
    ");
    $stmt_ind->bind_param("s",$receipt['reg_number']);
    $stmt_ind->execute();
    $stu_row=$stmt_ind->get_result()->fetch_assoc();
    $stmt_ind->close();
    $prev_total=floatval($connection->query("
        SELECT SUM(amount_paid) AS total_prev
        FROM fee_payment_receipts
        WHERE fee_payment_id={$receipt['fee_payment_id']} AND id<{$receipt_id}
    ")->fetch_assoc()['total_prev']??0);

    $remaining=floatval($stu_row['total_fee']??0)-$prev_total;
    $paid=min(floatval($receipt['amount_paid']),$remaining);
    $balance=round(max(0,$remaining-$paid),3);

    $students[]=[
        'name'=>trim($stu_row['firstname'].' '.$stu_row['othername'].' '.$stu_row['lastname']),
        'reg'=>$receipt['reg_number'],
        'class'=>$stu_row['class'],
        'total_fee'=>floatval($stu_row['total_fee']),
        'prev_paid'=>$prev_total,
        'remaining'=>$remaining,
        'paid'=>$paid,
        'balance'=>$balance
    ];

    $total_fee_all=$stu_row['total_fee'];
    $total_prev_paid_all=$prev_total;
    $total_paid_all=$paid;
}

// ====================
// Payment Info Box
$ref = $receipt['custom_ref'] ?: "STD_{$receipt['fee_payment_id']}";
$total_balance=round($total_fee_all-$total_prev_paid_all-$total_paid_all,3);
$status_text=($total_paid_all<=0)?"PENDING":(($total_balance<=0)?"PAID":"PART PAYMENT");
$status_color=($total_paid_all<=0)?"#d9534f":(($total_balance<=0)?"#28a745":"#6f42c1");
$amount_words=numberToWords(floatval($receipt['amount_paid']));

$html.='<table cellpadding="5" style="border:1px solid #ccc;border-radius:4px;width:100%;margin-bottom:8px;font-size:10px;">
<tr>
<td><strong>Reference:</strong> '.htmlspecialchars($ref).'</td>
<td style="text-align:right;"><strong>Family:</strong> '.htmlspecialchars($receipt['family_name']??'-').' | <strong>Family Reg No:</strong> '.($receipt['family_regno']??'-').'</td>
</tr>
<tr>
<td colspan="2" style="font-weight:bold;color:#d9534f;">
Receipt Amount: N'.number_format(floatval($receipt['amount_paid']),3).' 
<span style="background-color:'.$status_color.';color:#fff;padding:2px 6px;border-radius:4px;font-size:10px;margin-left:10px;">'.$status_text.'</span><br>
<em>Amount in Words: '.$amount_words.'</em>
</td>
</tr>
<tr>
<td><strong>Discount:</strong> '.($receipt['discount_percent']??0).'%</td>
<td></td>
</tr>
</table>';

// ====================
// Student Fee Table
$html .= '<table width="100%" cellpadding="5" style="border-collapse:collapse;border:1px solid #000;font-size:10px;">
<tr style="background-color:#f2f2f2;">
<th style="border:1px solid #000;">#</th>
<th style="border:1px solid #000;">Student Name</th>
<th style="border:1px solid #000;">Reg No / Family</th>
<th style="border:1px solid #000;">Class</th>
<th style="border:1px solid #000;text-align:right;">Total Fee</th>
<th style="border:1px solid #000;text-align:right;">Previous Payments</th>
<th style="border:1px solid #000;text-align:right;">Current Payments</th>
<th style="border:1px solid #000;text-align:right;">Balance</th>
</tr>';

foreach ($students as $index=>$stu){
    $html.='<tr>
<td style="border:1px solid #000;text-align:center;">'.($index+1).'</td>
<td style="border:1px solid #000;">'.htmlspecialchars($stu['name']).'</td>
<td style="border:1px solid #000;">'.htmlspecialchars($stu['reg']).'</td>
<td style="border:1px solid #000;">'.htmlspecialchars($stu['class']).'</td>
<td style="border:1px solid #000;text-align:right;">'.number_format($stu['total_fee'],3).'</td>
<td style="border:1px solid #000;text-align:right;">'.number_format($stu['prev_paid'],3).'</td>
<td style="border:1px solid #000;text-align:right;">'.number_format($stu['paid'],3).'</td>
<td style="border:1px solid #000;text-align:right;">'.number_format($stu['balance'],3).'</td>
</tr>';
}

// Totals
$html.='<tr style="font-weight:bold;background-color:#e6e6e6;">
<td colspan="4" style="border:1px solid #000;text-align:right;">TOTAL</td>
<td style="border:1px solid #000;text-align:right;">'.number_format($total_fee_all,3).'</td>
<td style="border:1px solid #000;text-align:right;">'.number_format($total_prev_paid_all,3).'</td>
<td style="border:1px solid #000;text-align:right;">'.number_format($total_paid_all,3).'</td>
<td style="border:1px solid #000;text-align:right;">'.number_format(max(0,$total_fee_all-$total_prev_paid_all-$total_paid_all),3).'</td>
</tr></table>';

// Footer
$html.='<div style="text-align:center;margin-top:10px;font-size:11px;"><em>Thank you for your payment!</em></div>
<div style="text-align:center;margin-top:6px;font-size:7px;color:#999;line-height:1.4;">
Developed by <strong>Taberah Technologies Limited</strong> | Phone: 09031449530<br>
Sponsored by <strong>Eduflow Consulting</strong>
</div>';

// ====================
// Write HTML to PDF
$pdf->writeHTML($html,true,false,true,false,'');
$pdf->Ln(5);

// Barcode
$pdf->write1DBarcode($ref,'C128','','','',20,0.5,
['position'=>'C','align'=>'C','stretch'=>false,'fitwidth'=>true,'border'=>false,'hpadding'=>'auto','vpadding'=>'auto','fgcolor'=>[0,0,0],'bgcolor'=>false,'text'=>true,'font'=>'helvetica','fontsize'=>10,'stretchtext'=>4],'N');

// Watermark Circle
$circle_x = 100;
$circle_y = $pdf->GetY()+25;
$radius = 12;
$pdf->SetFillColor(($total_balance<=0?40:217),($total_balance<=0?167:83),($total_balance<=0?64:79));
$pdf->SetTextColor(255,255,255);
$pdf->Circle($circle_x,$circle_y,$radius,0,360,'F');
$pdf->SetXY($circle_x-$radius,$circle_y-5);
$pdf->SetFont('helvetica','B',10);
$pdf->Cell($radius*2,10,($total_balance<=0?'CLEARED':'PENDING'),0,0,'C',0,'',0);

// Print
$pdf->IncludeJS("print(true);");
ob_end_clean();
$pdf->Output('Receipt_'.$ref.'.pdf','I');
?>