<?php
// print_invoice.php
ob_start();
session_start();
require 'includes/db.php'; // PDO instance $pdo

// ---------------- Auth & params ----------------
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}

$user_id    = intval($_SESSION['user_id']);
$user_role  = $_SESSION['user_role'] ?? '';
$visit_id   = intval($_GET['visit_id'] ?? 0);
$patient_id = intval($_GET['patient_id'] ?? 0);

if ($visit_id <= 0 || $patient_id <= 0) {
    die("Missing visit_id or patient_id");
}

// ---------------- Fetch facility ----------------
$facility_id = intval($_SESSION['facility_id'] ?? 0);
$stmt = $pdo->prepare("SELECT * FROM facility WHERE id=? LIMIT 1");
$stmt->execute([$facility_id]);
$facility = $stmt->fetch(PDO::FETCH_ASSOC);

$facility_name    = $facility['name'] ?? 'Facility Name';
$facility_tin     = $facility['tin_number'] ?? 'N/A';
$facility_phone   = $facility['facility_phone'] ?? 'N/A';
$facility_address = trim(($facility['province'] ?? '') . ' ' . ($facility['district'] ?? '') . ' ' . ($facility['sector'] ?? ''));

// ---------------- Helpers ----------------
function money($v) {
    return ' ' . number_format((float)$v, 2, '.', ',');
}
function h($s) {
    return htmlspecialchars($s ?? '', ENT_QUOTES, 'UTF-8');
}
function formatDateTime($datetime) {
    if (empty($datetime) || $datetime == '0000-00-00 00:00:00') {
        return 'N/A';
    }
    return date('Y-m-d H:i', strtotime($datetime));
}

// ---------------- Fetch patient ----------------
$stmt = $pdo->prepare("SELECT * FROM patients WHERE id=? LIMIT 1");
$stmt->execute([$patient_id]);
$patient = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$patient) die("Patient not found");

// ---------------- Fetch visit with doctor info ----------------
$stmt = $pdo->prepare("
    SELECT v.*, 
           ins.name AS insurance_name,
           u.username AS doctor_name,
           u.license_number AS doctor_license,
           u.phone AS doctor_phone
    FROM visits v
    LEFT JOIN insurance_partners ins ON ins.id = v.insurance_id
    LEFT JOIN users u ON u.id = v.treated_by
    WHERE v.id=? AND v.patient_id=? LIMIT 1
");
$stmt->execute([$visit_id, $patient_id]);
$visit = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$visit) die("Visit not found");

// ---------------- Percentages ----------------
$patient_percent   = (float)($visit['patient_co_pay_percentage'] ?? 0);
$insurance_percent = 100 - $patient_percent;

// ---------------- Fetch invoice items ----------------
$stmt = $pdo->prepare("
    SELECT i.*, p.name AS product_name
    FROM invoices i
    LEFT JOIN products p ON p.id = i.product_id
    WHERE i.visit_id=? 
      AND i.patient_id=? 
      AND i.product_id IS NOT NULL
      AND (i.is_removed IS NULL OR i.is_removed=0)
    ORDER BY i.created_at ASC
");
$stmt->execute([$visit_id, $patient_id]);
$items = $stmt->fetchAll(PDO::FETCH_ASSOC);

// ---------------- Remove FIRST ITEM (unchanged logic) ----------------
if (!empty($items)) {
    $items = array_slice($items, 1);
}

// ---------------- Totals (NO ROUNDING) ----------------
$total_amount   = 0.0;
$total_insurer  = 0.0;
$total_patient  = 0.0;
$total_paid     = 0.0;

foreach ($items as $it) {
    $amount        = (float)$it['amount'];
    $patient_share = (float)$it['patient_co_pay'];
    $insurance_shr = (float)$it['insurance_amount'];

    $total_amount  += $amount;
    $total_patient += $patient_share;
    $total_insurer += $insurance_shr;
    $total_paid    += (float)($it['amount_paid'] ?? 0);
}

// ---------------- Invoice number ----------------
$invoice_number = $visit['invoice_number'] ?? ('INV/DP/' . $visit_id . '/' . date('YmdHis'));

// ---------------- Current date/time for print footer ----------------
$print_date = date('Y-m-d H:i:s');
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Invoice - <?= h($patient['first_name'].' '.$patient['last_name']) ?></title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<style>
body{font-family:Arial,sans-serif;color:#111;margin:0;padding:0;font-size:12px;}
.container{width:210mm;margin:0 auto;padding:8mm;box-sizing:border-box;}
.header{display:flex;justify-content:space-between;align-items:center;margin-bottom:8px;}
.facility{font-weight:700;font-size:16px;}
.facility small{display:block;font-weight:400;font-size:10px;color:#333;}
.patient-info{margin-top:8px;display:flex;justify-content:space-between;}
.col{width:48%;}
.invoice-title{text-align:center;font-size:16px;font-weight:700;margin:6px 0;}
table{width:100%;border-collapse:collapse;margin-top:6px;font-size:11px;}
th,td{border:1px solid #000;padding:4px;}
th{background:#cfd6d3;text-align:left;}
.totals th,.totals td{padding:6px;font-size:12px;}
.right{text-align:right;}
.sig{margin-top:12px;display:flex;justify-content:space-between;}
.sig .box{width:48%;border-top:1px solid #777;padding-top:4px;color:#333;}
.print-controls{margin:8px 0;text-align:right;}
.btn{padding:6px 10px;background:#007bff;color:#fff;text-decoration:none;border-radius:4px;font-size:11px;}
.comment-col{max-width:120px;word-wrap:break-word;font-size:10px;}
.print-footer{text-align:center;font-size:10px;color:#666;margin-top:15px;border-top:1px dashed #ccc;padding-top:5px;}
.physician-info{font-size:11px;margin-bottom:8px;}
.physician-info strong{display:inline-block;width:80px;}
.physician-info .prefilled{border-bottom:1px solid #000;min-height:14px;margin-bottom:2px;}
.physician-info .blank-line{border-bottom:1px dashed #999;min-height:14px;margin-bottom:2px;}
@media print{.no-print{display:none!important;}}
</style>
</head>
<body>

<div class="container">

<div class="print-controls no-print">
    <a class="btn" href="#" onclick="window.print(); return false;">Print</a>
    <a class="btn" href="javascript:window.close();">Close</a>
</div>

<div class="header">
    <div>
        <div class="facility"><?= h($facility_name) ?></div>
        <small>
            TIN: <?= h($facility_tin) ?> | Phone: <?= h($facility_phone) ?>
            <?php if($facility_address): ?><br><?= h($facility_address) ?><?php endif; ?>
        </small>
    </div>
    <div style="text-align:right;">
        <div style="font-size:12px;">Patient Invoice</div>
        <div style="font-weight:700;margin-top:4px;"><?= h($invoice_number) ?></div>
    </div>
</div>

<div class="invoice-title">PATIENT INVOICE</div>

<div class="patient-info">
<div class="col">
    <strong>Patient:</strong>
    <?= h($patient['first_name'].' '.($patient['middle_name'] ?? '').' '.$patient['last_name']) ?><br>
    <strong>Gender:</strong> <?= h($patient['gender']) ?><br>
    <strong>DOB:</strong> <?= h($patient['d_o_b'] ?? 'N/A') ?><br>
    <strong>Phone:</strong> <?= h($patient['phone']) ?><br>
    <strong>File ID:</strong> <?= h($patient['file_id'] ?? '') ?>
</div>
<div class="col">
    <strong>Insurance:</strong> <?= h($visit['insurance_name'] ?? 'Self') ?><br>
    <strong>Visit Type:</strong> <?= h($visit['visit_type'] ?? '') ?> Patient<br>
    <strong>Insurance Card No:</strong> <?= h($visit['insurance_card_number'] ?? '') ?><br>
    <strong>Voucher No:</strong> <?= h($visit['voucher_id'] ?? '') ?><br>
    <strong>Disease:</strong> <?= h($visit['disease_type'] ?? '') ?><br>
    <strong>Visit Date:</strong> <?= formatDateTime($visit['visit_date']) ?><br>
    <strong>Discharge Time:</strong> 
    <?php 
        if (!empty($visit['discharge_time'])) {
            echo formatDateTime($visit['discharge_time']);
        } else {
            echo 'Not discharged';
        }
    ?>
</div>
</div>

<table>
<thead>
<tr>
<th>#</th><th>Description</th><th>Comment</th><th>Qty</th>
<th class="right">Unit Cost</th>
<th class="right">Total Amount</th>
<th class="right">Insurer Contr</th>
<th class="right">Patient Contr</th>
</tr>
</thead>
<tbody>
<?php if(empty($items)): ?>
<tr><td colspan="8" style="text-align:center;">No invoice items</td></tr>
<?php else: $i=1; foreach($items as $it): ?>
<tr>
<td><?= $i++ ?></td>
<td><?= h($it['product_name'] ?? 'Item') ?></td>
<td class="comment-col"><?= !empty($it['comment']) ? h($it['comment']) : '-' ?></td>
<td><?= h($it['quantity']) ?></td>
<td class="right"><?= money($it['price']) ?></td>
<td class="right"><?= money($it['amount']) ?></td>
<td class="right"><?= money($it['insurance_amount']) ?></td>
<td class="right"><?= money($it['patient_co_pay']) ?></td>
</tr>
<?php endforeach; endif; ?>
</tbody>
</table>

<table class="totals" style="margin-top:6px;">
<tr>
<th>Total Amount</th>
<th>Insurer Contr (<?= $insurance_percent ?>%)</th>
<th>Patient Contr(<?= $patient_percent ?>%)</th>
<th>Paid Amount</th>
<th>Balance</th>
</tr>
<tr>
<td style="font-weight:700;"><?= money($total_amount) ?><small>     RWF</small></td>
<td style="font-weight:700;text-align:center;"><?= money($total_insurer) ?> <small>RWF</small></td>
<td style="font-weight:700;text-align:center;"><?= money($total_patient) ?> <small>RWF</small></td>
<td style="font-weight:700;text-align:center;"><?= money($total_paid) ?> <small>RWF</small></td>
<td style="font-weight:700;text-align:center;"><?= money(max(0, $total_patient - $total_paid)) ?> <small>RWF</small></td>
</tr>
</table>

<br>

<div class="sig">
<div class="box">
<strong><u style="font-size: 15px;">Beneficiary</u></strong><br><br>
<strong>Affiliate Names:</strong> <?= h($visit['affiliate_name'] ?? '') ?><br><br>
<strong>Affiliate Affectation:</strong> <?= h($visit['affiliate_affectation'] ?? '') ?><br><br>
<strong>Beneficiary Relationship:</strong> <?= h($visit['beneficiary_relationship'] ?? '') ?><br><br>
<strong>Full Names:</strong> ___________________<br><br>
<strong>Phone Number:</strong> _______________________<br><br>
<strong>Signature:</strong> ___________________<br>
</div>

<div class="box">
<strong><u style="font-size: 15px;">Treated by</u></strong><br><br>
    
    <!-- Pre-filled physician information --> 
   <div class="physician-info">
    <?php if (!empty($visit['doctor_name'])): ?>
    <strong>Full Names:</strong> <?= h($visit['doctor_name']) ?><br><br>
    <?php endif; ?>
    
    <?php if (!empty($visit['doctor_license'])): ?>
    <strong>License Number:</strong> <?= h($visit['doctor_license']) ?><br><br>
    <?php endif; ?>
    
    <?php if (!empty($visit['doctor_phone'])): ?>
    <strong>Phone Number:</strong> <?= h($visit['doctor_phone']) ?><br><br>
    <?php endif; ?>
</div>
    
    <br>
    <strong>Stamp & Signature:</strong> _______________________________
</div>
</div>



</div>

<script>
window.onload=function(){setTimeout(()=>window.print(),300);}
</script>

</body>
</html>