<?php
ob_start();
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
session_start();
include('includes/db.php');
include('includes/header.php');

// ---------------- Auto Logout After 30 Minutes ----------------
$timeout_duration = 1800;
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY']) > $timeout_duration) {
    session_unset();
    session_destroy();
    header("Location: login.php?timeout=1");
    exit;
}
$_SESSION['LAST_ACTIVITY'] = time();

// ---------------- Check if user is logged in ----------------
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit;
}

/* ================= HELPER ================= */
function calculate_age($dob) {
    if (!$dob || $dob === '0000-00-00') return '';
    try {
        $dobDate = new DateTime($dob);
        $now = new DateTime();
        $diff = $now->diff($dobDate);
        if ($diff->y >= 1) return $diff->y . ' Year' . ($diff->y > 1 ? 's' : '');
        if ($diff->m >= 1) return $diff->m . ' Month' . ($diff->m > 1 ? 's' : '');
        return $diff->d . ' Day' . ($diff->d > 1 ? 's' : '');
    } catch (Exception $e) {
        return '';
    }
}

function format_currency($amount) {
    return number_format($amount, 2, '.', '');
}

// ---------------- CSRF Token ----------------
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
$csrf = $_SESSION['csrf_token'];

// ---------------- Current User Info ----------------
$user_id   = $_SESSION['user_id'];
$user_role = $_SESSION['user_role'];
$username  = $_SESSION['username'];
$facility_id = intval($_SESSION['facility_id'] ?? 0);

// ---------------- Get Patient ID & Visit ID ----------------
$patient_id = isset($_GET['patient_id']) ? intval($_GET['patient_id']) : 0;
if ($patient_id <= 0) die("Invalid request: patient_id is required.");

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

// ---------------- Fetch Visit ----------------
$visit_id = isset($_GET['visit_id']) ? intval($_GET['visit_id']) : 0;
if ($visit_id <= 0) {
    $stmt = $pdo->prepare("SELECT * FROM visits WHERE patient_id = ? ORDER BY visit_date DESC LIMIT 1");
    $stmt->execute([$patient_id]);
    $visit = $stmt->fetch(PDO::FETCH_ASSOC);
    $visit_id = $visit['id'] ?? 0;
} else {
    $stmt = $pdo->prepare("SELECT * FROM visits WHERE id = ? AND patient_id = ? LIMIT 1");
    $stmt->execute([$visit_id, $patient_id]);
    $visit = $stmt->fetch(PDO::FETCH_ASSOC);
}
if (!$visit) die("Visit not found for this patient.");

// ---------------- Visit closed flag ----------------
$visit_closed = ($visit['status'] ?? '') === 'closed';

// ---------------- Variables ----------------
$patient_co_pay_percentage = floatval($visit['patient_co_pay_percentage'] ?? 0);
$insurance_id = intval($visit['insurance_id'] ?? 0);

// ---------------- Fetch visit_tickets ----------------
$stmt = $pdo->prepare("SELECT * FROM visit_tickets WHERE visit_id = ? ORDER BY visit_date ASC");
$stmt->execute([$visit_id]);
$visit_tickets = $stmt->fetchAll(PDO::FETCH_ASSOC);

// ---------------- Fetch Lab Orders ----------------
$lab_orders = [];
if (count($visit_tickets) > 0) {
    $ticket_ids = array_map(fn($t)=>intval($t['id']), $visit_tickets);
    $placeholders = implode(',', array_fill(0, count($ticket_ids), '?'));
    
    // Fetch lab orders
    $sql = "SELECT lo.*, p.name AS product_name 
            FROM lab_orders lo 
            LEFT JOIN products p ON lo.product_id = p.id 
            WHERE lo.visit_ticket_id IN ($placeholders) 
            ORDER BY lo.created_at ASC";
    $stmt = $pdo->prepare($sql);
    $stmt->execute($ticket_ids);
    $lab_orders = $stmt->fetchAll(PDO::FETCH_ASSOC);
}

// ---------------- Fetch Products (facility-safe) - INCLUDING IMAGING ----------------
$stmt = $pdo->prepare("
    SELECT p.id, p.name, p.category_type, COALESCE(pip.price, p.price) AS price
    FROM products p
    LEFT JOIN product_insurance_prices pip 
        ON pip.product_id = p.id AND pip.insurance_partner_id = ?
    WHERE p.status='enabled' 
      AND p.facility_id = ?
      AND p.category_type IN ('drug', 'consumable', 'medical_act', 'imaging')
    ORDER BY p.category_type ASC, p.name ASC
");
$stmt->execute([$insurance_id, $facility_id]);
$products = $stmt->fetchAll(PDO::FETCH_ASSOC);

// ---------------- Ensure invoices table has proper columns ----------------
try {
    $pdo->exec("ALTER TABLE invoices ADD COLUMN IF NOT EXISTS lab_order_id INT DEFAULT NULL");
    $pdo->exec("ALTER TABLE invoices ADD COLUMN IF NOT EXISTS imaging_order_id INT DEFAULT NULL");
    $pdo->exec("ALTER TABLE invoices ADD COLUMN IF NOT EXISTS created_by INT UNSIGNED DEFAULT NULL");
    $pdo->exec("ALTER TABLE invoices ADD COLUMN IF NOT EXISTS facility_id INT DEFAULT NULL");
} catch (PDOException $e) {}

// ---------------- Auto-insert Lab Orders into Invoices ----------------
foreach ($lab_orders as $lo) {
    $lab_order_id = intval($lo['id']);
    $product_id = intval($lo['product_id']);
    if ($product_id <= 0) continue;

    $stmt = $pdo->prepare("SELECT id FROM invoices WHERE lab_order_id=? AND facility_id=? LIMIT 1");
    $stmt->execute([$lab_order_id, $facility_id]);
    if ($stmt->fetch()) continue;

    $stmt = $pdo->prepare("SELECT COALESCE((SELECT price FROM product_insurance_prices WHERE product_id=? AND insurance_partner_id=?), price) AS price FROM products WHERE id=?");
    $stmt->execute([$product_id, $insurance_id, $product_id]);
    $price = floatval($stmt->fetchColumn()) ?: 0.00;

    $quantity = floatval($lo['quantity'] ?? 1) ?: 1;
    $amount = $price * $quantity;
    $patient_pay = $amount * ($patient_co_pay_percentage / 100);
    $insurance_pay = $amount - $patient_pay;

    $invoice_number = 'LAB-' . $lab_order_id . '-' . $visit_id . '-' . time() . '-' . rand(100,999);

    $stmt = $pdo->prepare("
        INSERT INTO invoices 
        (invoice_number, visit_id, patient_id, product_id, quantity, price, amount, patient_co_pay, insurance_amount, amount_paid, status, is_removed, created_at, lab_order_id, created_by, facility_id)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 0.00, 'unpaid', 0, NOW(), ?, ?, ?)
    ");
    try {
        $stmt->execute([$invoice_number, $visit_id, $patient_id, $product_id, $quantity, $price, $amount, $patient_pay, $insurance_pay, $lab_order_id, $user_id, $facility_id]);
    } catch (PDOException $e) {}
}

// ---------------- Fetch Invoices ----------------
$stmt = $pdo->prepare("
    SELECT i.*, 
           p.name AS product_name, 
           COALESCE(pip.price, p.price) AS product_price, 
           u.username AS created_by_name,
           p.category_type
    FROM invoices i
    LEFT JOIN products p ON i.product_id = p.id
    LEFT JOIN product_insurance_prices pip ON pip.product_id=p.id AND pip.insurance_partner_id=?
    LEFT JOIN users u ON i.created_by=u.id
    WHERE i.visit_id=? AND i.patient_id=? AND (i.is_removed IS NULL OR i.is_removed=0) AND i.facility_id=?
    ORDER BY i.created_at ASC
");
$stmt->execute([$insurance_id,$visit_id,$patient_id,$facility_id]);
$invoices = $stmt->fetchAll(PDO::FETCH_ASSOC);

// ---------------- Handle Add Product ----------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_product'])) {
    if ($visit_closed) {
        $_SESSION['flash'] = ['message' => 'Cannot add product. Visit is closed.', 'color' => '#ffc107'];
        header("Location: invoices.php?patient_id={$patient_id}&visit_id={$visit_id}"); exit;
    }
    if (!isset($_POST['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) die('Invalid CSRF token');

    $product_id = intval($_POST['product_id']);
    $quantity = floatval($_POST['quantity']) ?: 1;
    $comment = trim($_POST['comment'] ?? '');

    $stmt = $pdo->prepare("
        SELECT COUNT(*) 
        FROM invoices 
        WHERE visit_id=? AND product_id=? AND patient_id=? 
          AND (is_removed IS NULL OR is_removed=0) 
          AND facility_id=?
    ");
    $stmt->execute([$visit_id, $product_id, $patient_id, $facility_id]);
    if ($stmt->fetchColumn() > 0) {
        $_SESSION['flash'] = ['message' => 'This product is already added!', 'color' => '#ffc107'];
        header("Location: invoices.php?patient_id={$patient_id}&visit_id={$visit_id}"); exit;
    }

    $stmt = $pdo->prepare("
        SELECT p.name, p.category_type, COALESCE(pip.price, p.price) AS price
        FROM products p
        LEFT JOIN product_insurance_prices pip 
            ON pip.product_id = p.id AND pip.insurance_partner_id = ?
        WHERE p.id=? AND p.status='enabled'
        LIMIT 1
    ");
    $stmt->execute([$insurance_id, $product_id]);
    $product = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$product) {
        $_SESSION['flash'] = ['message' => 'Product not found!', 'color' => '#dc3545'];
        header("Location: invoices.php?patient_id={$patient_id}&visit_id={$visit_id}"); exit;
    }

    // ---------------- Stock check for drugs/consumables only ----------------
    if (in_array($product['category_type'], ['drug','consumable'])) {
        $stmt = $pdo->prepare("
            SELECT COALESCE(SUM(stock_in - stock_out),0) AS available_stock 
            FROM stock 
            WHERE product_id=? AND facility_id=? AND status='enabled'
        ");
        $stmt->execute([$product_id, $facility_id]);
        $available_stock = intval($stmt->fetchColumn());

        if ($available_stock < $quantity) {
            $_SESSION['flash'] = ['message' => "Not enough stock for {$product['name']}. Available: {$available_stock}", 'color' => '#ffc107'];
            header("Location: invoices.php?patient_id={$patient_id}&visit_id={$visit_id}"); exit;
        }

        $stmt = $pdo->prepare("
            SELECT id, stock_in, stock_out
            FROM stock
            WHERE product_id = ?
              AND facility_id = ?
              AND status = 'enabled'
            ORDER BY created_at ASC
            LIMIT 1
        ");
        $stmt->execute([$product_id, $facility_id]);
        $stock = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$stock) {
            $_SESSION['flash'] = [
                'message' => "No stock available for {$product['name']}",
                'color'   => '#ffc107'
            ];
            header("Location: invoices.php?patient_id={$patient_id}&visit_id={$visit_id}");
            exit;
        }

        $available = $stock['stock_in'] - $stock['stock_out'];

        if ($available < $quantity) {
            $_SESSION['flash'] = [
                'message' => "Not enough stock for {$product['name']}. Available: {$available}",
                'color'   => '#ffc107'
            ];
            header("Location: invoices.php?patient_id={$patient_id}&visit_id={$visit_id}");
            exit;
        }

        $stmt = $pdo->prepare("
            UPDATE stock
            SET stock_out = stock_out + ?,
                decreased_by = ?,
                note = CONCAT(IFNULL(note,''), ' | Sold via invoice')
            WHERE id = ?
        ");
        $stmt->execute([
            $quantity,
            $user_id,
            $stock['id']
        ]);
    }
    
    // ---------------- NO STOCK CHECK FOR IMAGING & MEDICAL ACT ----------------
    // Imaging and medical acts can be added without stock checks

    // ---------------- Calculate price and invoice ----------------
    $price = floatval($product['price']);
    $amount = $price * $quantity;
    $patient_pay = $amount * ($patient_co_pay_percentage / 100);
    $insurance_pay = $amount - $patient_pay;
    $invoice_number = 'INV-' . $visit_id . '-' . time() . '-' . rand(100, 999);

    $stmt = $pdo->prepare("
        INSERT INTO invoices 
        (invoice_number, visit_id, patient_id, product_id, quantity, price, amount, patient_co_pay, insurance_amount, amount_paid, status, is_removed, created_at, created_by, facility_id, comment)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 0.00, 'unpaid', 0, NOW(), ?, ?, ?)
    ");
    $stmt->execute([$invoice_number, $visit_id, $patient_id, $product_id, $quantity, $price, $amount, $patient_pay, $insurance_pay, $user_id, $facility_id, $comment]);

    $_SESSION['flash'] = ['message' => 'Product added!', 'color' => '#28a745'];
    header("Location: invoices.php?patient_id={$patient_id}&visit_id={$visit_id}"); exit;
}

// ---------------- Handle Restore Invoice ----------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['restore_invoice'])) {
    if (!in_array($user_role, ['Admin','Super_admin'])) {
        $_SESSION['flash'] = ['message'=>'Not allowed to restore','color'=>'#dc3545'];
        header("Location: invoices.php?patient_id={$patient_id}&visit_id={$visit_id}");
        exit;
    }

    if (!isset($_POST['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token']))
        die('Invalid CSRF token');

    $invoice_id = intval($_POST['invoice_id']);

    $stmt = $pdo->prepare("
        SELECT i.*, p.category_type
        FROM invoices i
        LEFT JOIN products p ON i.product_id=p.id
        WHERE i.id=? AND i.is_removed=1 AND i.facility_id=?
        LIMIT 1
    ");
    $stmt->execute([$invoice_id,$facility_id]);
    $inv = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$inv) {
        $_SESSION['flash'] = ['message'=>'Invoice not found','color'=>'#dc3545'];
        header("Location: invoices.php?patient_id={$patient_id}&visit_id={$visit_id}");
        exit;
    }

    // Deduct stock again for drugs/consumables ONLY
    if (in_array($inv['category_type'], ['drug','consumable'])) {
        $stmt = $pdo->prepare("
            SELECT COALESCE(SUM(stock_in-stock_out),0)
            FROM stock
            WHERE product_id=? AND facility_id=?
        ");
        $stmt->execute([$inv['product_id'],$facility_id]);
        $available = intval($stmt->fetchColumn());

        if ($available < $inv['quantity']) {
            $_SESSION['flash'] = ['message'=>'Not enough stock to restore','color'=>'#ffc107'];
            header("Location: invoices.php?patient_id={$patient_id}&visit_id={$visit_id}");
            exit;
        }

        $stmt = $pdo->prepare("
            INSERT INTO stock
            (product_id, stock_in, stock_out, note, created_at, created_by, facility_id)
            VALUES (?, 0, ?, ?, NOW(), ?, ?)
        ");
        $stmt->execute([
            $inv['product_id'],
            $inv['quantity'],
            'Stock deducted after invoice restore',
            $user_id,
            $facility_id
        ]);
    }
    // NO STOCK UPDATE FOR IMAGING & MEDICAL ACT

    $stmt = $pdo->prepare("
        UPDATE invoices 
        SET is_removed=0 
        WHERE id=? AND facility_id=?
    ");
    $stmt->execute([$invoice_id,$facility_id]);

    $_SESSION['flash'] = ['message'=>'Invoice restored successfully','color'=>'#28a745'];
    header("Location: invoices.php?patient_id={$patient_id}&visit_id={$visit_id}");
    exit;
}

// ---------------- Handle Remove Product (SOFT DELETE) ----------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['remove_invoice'])) {
    if ($visit_closed) {
        $_SESSION['flash'] = ['message' => 'Cannot remove product. Visit is closed.', 'color' => '#ffc107'];
        header("Location: invoices.php?patient_id={$patient_id}&visit_id={$visit_id}");
        exit;
    }

    if (!isset($_POST['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token']))
        die('Invalid CSRF token');

    $invoice_id = intval($_POST['invoice_id']);

    $stmt = $pdo->prepare("
        SELECT i.*, p.category_type 
        FROM invoices i
        LEFT JOIN products p ON i.product_id = p.id
        WHERE i.id=? AND i.facility_id=?
        LIMIT 1
    ");
    $stmt->execute([$invoice_id, $facility_id]);
    $invoice = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$invoice) {
        $_SESSION['flash'] = ['message' => 'Invoice not found!', 'color' => '#dc3545'];
        header("Location: invoices.php?patient_id={$patient_id}&visit_id={$visit_id}");
        exit;
    }

    // Check permissions
    if ($user_role === 'Super_admin' || $user_role === 'Admin') {
        // Admins can remove product regardless of payment
    } elseif ($user_role === 'Receptionist') {
        // Receptionist can only remove unpaid products
        if ($invoice['amount_paid'] > 0) {
            $_SESSION['flash'] = [
                'message' => 'Cannot remove product. Payment already exists!',
                'color' => '#ffc107'
            ];
            header("Location: invoices.php?patient_id={$patient_id}&visit_id={$visit_id}");
            exit;
        }
    } else {
        // All other roles cannot remove
        $_SESSION['flash'] = [
            'message' => 'You are not allowed to remove this product!',
            'color' => '#ffc107'
        ];
        header("Location: invoices.php?patient_id={$patient_id}&visit_id={$visit_id}");
        exit;
    }

    // Restore stock for drugs/consumables ONLY
    if (in_array($invoice['category_type'], ['drug','consumable'])) {
        $quantity = floatval($invoice['quantity']);

        $stmt = $pdo->prepare("
            SELECT id, stock_in, stock_out
            FROM stock
            WHERE product_id=? AND facility_id=? AND status='enabled'
            ORDER BY created_at DESC
            LIMIT 1
        ");
        $stmt->execute([$invoice['product_id'], $facility_id]);
        $last_stock = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($last_stock) {
            $stmt_up = $pdo->prepare("
                UPDATE stock
                SET stock_out = stock_out - ?, note=?
                WHERE id=?
            ");
            $stmt_up->execute([
                $quantity,
                'Restored stock after invoice removal',
                $last_stock['id']
            ]);
        }
    }
    // NO STOCK RESTORE FOR IMAGING & MEDICAL ACT

    // Soft delete
    $stmt = $pdo->prepare("
        UPDATE invoices 
        SET is_removed=1 
        WHERE id=? AND facility_id=?
    ");
    $stmt->execute([$invoice_id, $facility_id]);

    $_SESSION['flash'] = ['message' => 'Product removed (can be restored).', 'color' => '#dc3545'];
    header("Location: invoices.php?patient_id={$patient_id}&visit_id={$visit_id}");
    exit;
}

// ---------------- Handle Record Payment ----------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['record_payment'])) {
    if ($visit_closed) { 
        $_SESSION['flash'] = ['message' => 'Cannot record payment. Visit is closed.', 'color' => '#ffc107'];
        header("Location: invoices.php?patient_id={$patient_id}&visit_id={$visit_id}"); 
        exit; 
    }
    
    if (!in_array($user_role, ['Receptionist', 'Admin', 'Super_admin'])) {
        $_SESSION['flash'] = [
            'message' => 'Only Receptionists, Admins, or Super Admins can record payments!',
            'color'   => '#ffc107'
        ];
        header("Location: invoices.php?patient_id={$patient_id}&visit_id={$visit_id}");
        exit;
    }

    if (!isset($_POST['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) 
        die('Invalid CSRF token');

    $amount_to_pay = floatval($_POST['amount_paid']);
    $payment_method = trim($_POST['payment_method'] ?? '');

    if ($amount_to_pay <= 0 || empty($payment_method)) { 
        $_SESSION['flash'] = ['message' => 'Enter a valid amount and select a payment method.', 'color' => '#ffc107']; 
        header("Location: invoices.php?patient_id={$patient_id}&visit_id={$visit_id}"); 
        exit; 
    }

    $stmt = $pdo->prepare("SELECT * FROM invoices WHERE visit_id=? AND patient_id=? AND product_id IS NOT NULL AND (is_removed IS NULL OR is_removed=0) ORDER BY created_at ASC");
    $stmt->execute([$visit_id, $patient_id]);
    $invoice_rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    if (!$invoice_rows) { 
        $_SESSION['flash'] = ['message' => 'No invoices to pay.', 'color' => '#ffc107']; 
        header("Location: invoices.php?patient_id={$patient_id}&visit_id={$visit_id}"); 
        exit; 
    }

    $total_patient_due = 0;
    foreach ($invoice_rows as $r) 
        $total_patient_due += max(0, round(floatval($r['patient_co_pay']) - floatval($r['amount_paid']), 2));
    
    if ($total_patient_due <= 0) { 
        $_SESSION['flash'] = ['message' => 'Patient already fully paid.', 'color' => '#ffc107']; 
        header("Location: invoices.php?patient_id={$patient_id}&visit_id={$visit_id}"); 
        exit; 
    }

    if ($amount_to_pay > $total_patient_due) 
        $amount_to_pay = $total_patient_due;

    try {
        $pdo->beginTransaction();
        $remaining_payment = $amount_to_pay;

        foreach ($invoice_rows as $inv_row) {
            if ($remaining_payment <= 0) break;

            $inv_id = intval($inv_row['id']);
            $remaining_inv = max(0, round(floatval($inv_row['patient_co_pay']) - floatval($inv_row['amount_paid']), 2));
            if ($remaining_inv <= 0) continue;

            $allocate = min($remaining_inv, $remaining_payment);
            $new_paid = round(floatval($inv_row['amount_paid']) + $allocate, 2);
            $new_status = ($new_paid >= round(floatval($inv_row['patient_co_pay']), 0)) ? 'complete' : 'unpaid';

            $stmt_up = $pdo->prepare("UPDATE invoices SET amount_paid=?, status=?, payment_method=? WHERE id=?");
            $stmt_up->execute([$new_paid, $new_status, $payment_method, $inv_id]);

            $remaining_payment = round($remaining_payment - $allocate, 2);
        }

        $pdo->commit();
    } catch (PDOException $e) {
        $pdo->rollBack();
        $_SESSION['flash'] = ['message' => 'Failed to record payment: ' . $e->getMessage(), 'color' => '#dc3545'];
        header("Location: invoices.php?patient_id={$patient_id}&visit_id={$visit_id}");
        exit;
    }

    $_SESSION['flash'] = ['message' => 'Payment recorded successfully!', 'color' => '#28a745'];
    header("Location: invoices.php?patient_id={$patient_id}&visit_id={$visit_id}");
    exit;
}

// ---------------- Handle Delete Payment ----------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_payment'])) {
    if ($visit_closed) {
        $_SESSION['flash'] = ['message' => 'Cannot delete payment. Visit is closed.', 'color' => '#ffc107'];
        header("Location: invoices.php?patient_id={$patient_id}&visit_id={$visit_id}"); exit;
    }

    if (!isset($_POST['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) die('Invalid CSRF token');

    $amount_to_delete = floatval($_POST['amount_to_delete']);
    if ($amount_to_delete <= 0) {
        $_SESSION['flash'] = ['message' => 'Invalid amount to delete.', 'color' => '#ffc107'];
        header("Location: invoices.php?patient_id={$patient_id}&visit_id={$visit_id}"); exit;
    }

    try {
        $pdo->beginTransaction();

        $stmt = $pdo->prepare("SELECT id, amount_paid, patient_co_pay FROM invoices WHERE visit_id=? AND patient_id=? AND amount_paid>0 ORDER BY created_at DESC");
        $stmt->execute([$visit_id,$patient_id]);
        $paid_invoices = $stmt->fetchAll(PDO::FETCH_ASSOC);

        $remaining = $amount_to_delete;
        foreach ($paid_invoices as $inv) {
            if ($remaining <= 0) break;

            $deduct = min($inv['amount_paid'], $remaining);
            $new_paid = round($inv['amount_paid'] - $deduct,2);
            $new_status = ($new_paid >= round(floatval($inv['patient_co_pay']),0)) ? 'complete' : 'unpaid';

            $stmt_up = $pdo->prepare("UPDATE invoices SET amount_paid=?, status=? WHERE id=?");
            $stmt_up->execute([$new_paid, $new_status, $inv['id']]);

            $remaining -= $deduct;
        }

        $pdo->commit();
        $_SESSION['flash'] = ['message' => 'Payment deleted successfully!', 'color'=>'#28a745'];
    } catch(PDOException $e) {
        $pdo->rollBack();
        $_SESSION['flash'] = ['message' => 'Failed to delete payment: '.$e->getMessage(),'color'=>'#dc3545'];
    }

    header("Location: invoices.php?patient_id={$patient_id}&visit_id={$visit_id}");
    exit;
}

// ---------------- Calculate Totals ----------------
$total_amount=$total_patient=$total_insurance=$total_paid=0;
foreach ($invoices as $inv) {
    if(empty($inv['product_id'])) continue;
    $total_amount+=floatval($inv['amount']);
    $total_patient+=floatval($inv['patient_co_pay']);
    $total_insurance+=floatval($inv['insurance_amount']);
    $total_paid+=floatval($inv['amount_paid']);
}
$total_amount=round($total_amount,2);
$total_patient=round($total_patient,2);
$total_insurance=round($total_insurance,2);
$total_paid=round($total_paid,2);
$patient_fully_paid=($total_patient>0 && $total_paid>=$total_patient);
?>

<!-- ================= HEADER & SIDEBAR ================= -->
<nav class="header-navbar navbar navbar-with-menu navbar-fixed-top navbar-semi-dark navbar-shadow">
    <?php include('includes/navbar.php'); ?>
</nav>

<div data-scroll-to-active="true" class="main-menu menu-fixed menu-dark menu-accordion menu-shadow">
    <?php include('includes/sidebar.php'); ?>
</div>

<div class="app-content content container-fluid">
<div class="content-wrapper">

<!-- ================= PAGE TITLE ================= -->
<h2 class="text-center mb-2">
    Invoices for Patient:
    <?= htmlspecialchars($patient['first_name'].' '.($patient['middle_name'] ?: '').' '.$patient['last_name']) ?>
    <br>
    <small>
        Visit #: <?= htmlspecialchars($visit['id']) ?>
        | Visit Date: <?= htmlspecialchars($visit['visit_date'] ?? '') ?>
    </small>
</h2>

<hr>

<?php include('visit_ticket_info.php'); ?>

<div class="row">
<div class="col-md-12">
<div class="card">

<!-- ================= CARD HEADER ================= -->
<div class="card-header d-flex justify-content-between align-items-center">
    <h4 class="mb-0">Invoice Items (Visit Invoice)</h4>
    <div>
        <button type="button" class="btn btn-sm btn-primary" data-toggle="modal" data-target="#addItemModal">
            Add Item
        </button>

        <?php if ($total_patient == 0): ?>
            <span class="btn btn-sm btn-secondary">No patient co-pay yet</span>
        <?php elseif ($patient_fully_paid): ?>
            <span class="btn btn-sm btn-success">PAID</span>
        <?php else: ?>
            <span class="btn btn-sm btn-danger">UNPAID</span>
        <?php endif; ?>

        <button class="btn btn-sm btn-info"
            onclick="window.open(
                'print_invoice.php?patient_id=<?= $patient_id ?>&visit_id=<?= $visit_id ?>',
                '_blank'
            )">
            Print Invoice
        </button>
    </div>
</div>

<!-- ================= INVOICE TABLE ================= -->
<div class="card-body p-1" style="max-height:520px; overflow-y:auto;">

<?php if (!empty($invoices)): ?>
<div class="table-responsive">
<table class="table table-bordered table-sm mb-0" id="invoiceTable">
<thead class="thead-dark">
<tr>
    <th>#</th>
    <th>Product/Service</th>
    <th>Comment</th>
    <th>Type</th>
    <th>Qty</th>
    <th>Price (RWF)</th>
    <th>Total (RWF)</th>
    <th>Patient (RWF)</th>
    <th>Insurance (RWF)</th>
    <th>Paid (RWF)</th>
    <th>Action</th>
</tr>
</thead>

<tbody>
<?php $i = 1; foreach ($invoices as $inv): ?>
<?php
if (empty($inv['product_id'])) continue;

$amount          = (float)$inv['amount'];
$patient_co_pay  = (float)$inv['patient_co_pay'];
$insurance       = (float)$inv['insurance_amount'];
$paid            = (float)$inv['amount_paid'];

$row_class = ($paid >= $patient_co_pay) ? 'table-success' : 'table-danger';

// Determine product type for display
$product_type = $inv['category_type'] ?? 'unknown';
$type_badge = '';
switch($product_type) {
    case 'drug': $type_badge = '<span class="badge badge-info">Drug</span>'; break;
    case 'consumable': $type_badge = '<span class="badge badge-secondary">Consumable</span>'; break;
    case 'medical_act': $type_badge = '<span class="badge badge-primary">Medical Act</span>'; break;
    case 'imaging': $type_badge = '<span class="badge badge-dark">Imaging</span>'; break;
    default: $type_badge = '<span class="badge badge-light">Other</span>';
}

/* Delete permission rules */
$allow_delete = false;
if (in_array($user_role, ['Admin','Super_admin']) && !$visit_closed) {
    $allow_delete = true;
} elseif (
    $user_role === 'Receptionist' &&
    $inv['status'] !== 'paid' &&
    empty($inv['lab_order_id']) &&
    empty($inv['imaging_order_id'])
) {
    $allow_delete = true;
}
?>

<tr class="<?= $row_class ?> text-center">
    <td><?= $i++ ?></td>
    <td style="text-align:left;">
        <?= htmlspecialchars($inv['product_name']) ?>
    </td>
    <td style="text-align:left;">
        <?= !empty($inv['comment']) ? htmlspecialchars($inv['comment']) : '<span class="text-muted">No comment</span>' ?>
    </td>
    <td><?= $type_badge ?></td>
    <td><?= htmlspecialchars($inv['quantity']) ?></td>
    <td><?= format_currency($inv['price']) ?></td>
    <td><?= format_currency($amount) ?></td>
    <td><?= format_currency($patient_co_pay) ?></td>
    <td><?= format_currency($insurance) ?></td>
    <td><?= format_currency($paid) ?></td>
    <td style="min-width:120px;">
        <?php if ($allow_delete): ?>
            <form method="POST" class="d-inline">
                <input type="hidden" name="csrf_token" value="<?= $csrf ?>">
                <input type="hidden" name="invoice_id" value="<?= (int)$inv['id'] ?>">
                <button type="submit" name="remove_invoice" class="btn btn-sm btn-danger">
                    <i class="icon-trash2"></i>
                </button>
            </form>
        <?php elseif (!empty($inv['lab_order_id']) || !empty($inv['imaging_order_id'])): ?>
            <span class="text-muted">
                <i class="icon-trash2 btn btn-sm btn-grey"></i>
            </span>
        <?php else: ?>
            <span class="text-muted">—</span>
        <?php endif; ?>
    </td>
</tr>

<?php endforeach; ?>
</tbody>

<tfoot>
<tr>
    <th colspan="6" class="text-right">Totals:</th>
    <th><?= format_currency($total_amount) ?></th>
    <th><?= format_currency($total_patient) ?></th>
    <th><?= format_currency($total_insurance) ?></th>
    <th><?= format_currency($total_paid) ?></th>
    <th></th>
</tr>
</tfoot>

</table>
</div>
<?php else: ?>
<p class="text-muted">No products added to this visit invoice yet.</p>
<?php endif; ?>

<!-- ================= PAYMENT FORM ================= -->
<?php if($total_patient > 0 && !$patient_fully_paid): ?>
<div class="card mt-2 p-3">
    <h5>Patient Payment (Patient Co-Pay)</h5>
    <p style="margin-bottom:6px;">
        Total patient co-pay: <strong style="color: blue"><?= format_currency($total_patient) ?> Rwf</strong> | Already paid: <strong style="color: green"><?= format_currency($total_paid) ?> Rwf</strong> | Remaining: <strong style="color: red"><?= format_currency(max(0, round($total_patient - $total_paid,2))) ?> Rwf</strong>
    </p>

    <form method="POST" class="row">
        <input type="hidden" name="csrf_token" value="<?= $csrf ?>">
        <div class="col-md-4">
            <div class="form-group">
                <label>Amount to Pay</label>
                <input type="number" step="0.01" name="amount_paid" class="form-control" min="0.01" max="<?= number_format(max(0, round($total_patient - $total_paid,2)),2,'.','') ?> " required placeholder="<?= number_format(max(0, round($total_patient - $total_paid,2)),2) ?> Rwf">
            </div>
        </div>

        <div class="col-md-4">
            <div class="form-group">
                <label>Payment Method</label>
                <select name="payment_method" class="form-control" required>
                    <option value="">-- Select Method --</option>
                    <option>Cash</option>
                    <option>Mobile Money</option>
                    <option>Airtel Money</option>
                    <option>Card</option>
                    <option>Bank Card</option>
                    <option>Bank Transfer</option>
                    <option>Credit</option>
                </select>
            </div>
        </div>

        <?php if (in_array($user_role, ['Receptionist', 'Admin', 'Super_admin'])): ?>
            <div class="col-md-4 d-flex align-items-end">
                <button type="submit" name="record_payment" class="btn btn-success btn-block">
                    Pay Now
                </button>
            </div>
        <?php endif; ?>
    </form>
</div>
<?php endif; ?>

<!-- ================= PAYMENT SUMMARY ================= -->
<?php
$total_paid_amount = 0;
$payments = [];

foreach ($invoices as $inv) {
    if (empty($inv['product_id']) || !empty($inv['is_removed'])) continue;
    if ((float)$inv['amount_paid'] > 0) {
        $payments[] = $inv;
        $total_paid_amount += (float)$inv['amount_paid'];
    }
}

$remaining = max(0, $total_patient - $total_paid_amount);
?>

<div class="card mt-3 p-3">
<h5>Payment Summary</h5>

<p>
    <strong>Total Co-Pay:</strong> <?= format_currency($total_patient) ?> <small>Rwf</small><br>
    <strong>Total Paid:</strong> <?= format_currency($total_paid_amount) ?> <small>Rwf</small><br>
    <strong>Remaining:</strong> <?= format_currency($remaining) ?> <small>Rwf</small>
</p>

<?php if ($payments): ?>
<div class="table-responsive">
<table class="table table-bordered table-sm">
<thead>
<tr>
    <th>#</th>
    <th>Amount</th>
    <th>Method</th>
    <th>Paid By</th>
    <th>Date</th>
    <th>Action</th>
</tr>
</thead>
<tbody>
<?php foreach ($payments as $k => $p): ?>
<tr>
    <td><?= $k + 1 ?></td>
    <td><?= format_currency($p['amount_paid']) ?></td>
    <td><?= htmlspecialchars($p['payment_method']) ?></td>
    <td><?= htmlspecialchars($p['created_by_name'] ?? '—') ?></td>
    <td><?= date('d M Y H:i', strtotime($p['created_at'])) ?></td>
    <td>
        <?php if (in_array($user_role,['Admin','Super_admin'])): ?>
        <form method="POST" class="d-inline">
            <input type="hidden" name="csrf_token" value="<?= $csrf ?>">
            <input type="hidden" name="amount_to_delete" value="<?= $p['amount_paid'] ?>">
            <button type="submit" name="delete_payment" class="btn btn-sm btn-danger" title="Delete Payment">
                <i class="icon-trash2"></i>
            </button>
        </form>
        <?php else: ?>
        <span class="text-muted">—</span>
        <?php endif; ?>
    </td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<?php else: ?>
<p class="text-muted">No payments recorded.</p>
<?php endif; ?>
</div>

</div>
</div>
</div>
</div>
</div>
</div>

<!-- ================= ADD ITEM MODAL ================= -->
<div class="modal fade" id="addItemModal" tabindex="-1" role="dialog" aria-labelledby="addItemModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg" role="document">
    <div class="modal-content">
      <form method="POST">
        <input type="hidden" name="csrf_token" value="<?= $csrf ?>">
        <input type="hidden" name="visit_id" value="<?= $visit_id ?>">
        <div class="modal-header">
          <h5 class="modal-title" id="addItemModalLabel">Add Item to Invoice</h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        <div class="modal-body">
            <!-- Product Select -->
            <div class="form-group">
                <label>Select Product/Service</label>
                <select name="product_id" class="form-control select2" required>
                    <option value="" disabled selected>-- Select Item --</option>
                    <?php foreach($products as $p): 
                        $type_color = '';
                        $stock_info = '';
                        $include_product = true;
                        $available_stock = 0;
                        $nearest_expiry_formatted = 'N/A';

                        // Check stock for drugs & consumables ONLY
                        if (in_array($p['category_type'], ['drug','consumable'])) {
                            $stmt = $pdo->prepare("
                                SELECT COALESCE(SUM(stock_in - stock_out),0) AS available_stock,
                                       MIN(expiration_date) AS nearest_expiry
                                FROM stock 
                                WHERE product_id=? 
                                  AND status='enabled' 
                                  AND facility_id=? 
                                  AND (expiration_date IS NULL OR expiration_date >= CURDATE())
                            ");
                            $stmt->execute([$p['id'], $facility_id]);
                            $stock_data = $stmt->fetch(PDO::FETCH_ASSOC);

                            $available_stock = intval($stock_data['available_stock']);
                            $nearest_expiry = $stock_data['nearest_expiry'] ?? 'N/A';
                            $nearest_expiry_formatted = ($nearest_expiry && $nearest_expiry!=='0000-00-00') ? date('d-M-Y', strtotime($nearest_expiry)) : 'N/A';

                            if ($available_stock <= 0) $include_product = false;
                            $stock_info = " | Stock: {$available_stock} | Exp: {$nearest_expiry_formatted}";
                            $type_color = $p['category_type'] === 'drug' ? '#d1ecf1' : '#d4edda';
                        } else {
                            // For imaging and medical acts - NO stock info needed
                            $stock_info = "";
                        }

                        if (!$include_product) continue;

                        // Type label
                        $type_label = '';
                        switch($p['category_type']) {
                            case 'drug': $type_label = '[DRUG]'; break;
                            case 'consumable': $type_label = '[CONSUMABLE]'; break;
                            case 'medical_act': $type_label = '[MEDICAL ACT]'; break;
                            case 'imaging': $type_label = '[IMAGING]'; break;
                            default: $type_label = '[OTHER]';
                        }
                    ?>
                        <option 
                            value="<?= $p['id'] ?>" 
                            data-color="<?= $type_color ?>" 
                            data-stock="<?= $available_stock ?>" 
                            data-expiry="<?= $nearest_expiry_formatted ?>">
                            <?= htmlspecialchars($p['name']) ?> <?= $type_label ?>
                            (<?= number_format($p['price'],0) ?> RWF<?= $stock_info ?>)
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <!-- Quantity -->
            <div class="form-group">
                <label>Quantity</label>
                <input type="number" name="quantity" class="form-control" min="1" value="1" required>
            </div>

            <!-- Comment -->
            <div class="form-group">
                <label>Comment (Optional)</label>
                <textarea name="comment" class="form-control" rows="2" placeholder="Add any notes about this item..."></textarea>
            </div>
        </div>
        <div class="modal-footer">
          <button type="submit" name="add_product" class="btn btn-primary">Add Item</button>
          <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        </div>
      </form>
    </div>
  </div>
</div>

<?php include('includes/footer.php'); ?>

<!-- ================== SELECT2 INCLUDES ================== -->
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

<script>
$(document).ready(function() {
    // Initialize Select2 when modal is shown
    $('#addItemModal').on('shown.bs.modal', function () {
        $(this).find('.select2').select2({
            width: '100%',
            placeholder: "-- Select Item --",
            allowClear: true,
            dropdownParent: $(this)
        });
    });

    <?php if(isset($_SESSION['flash'])): ?>
        const toast = document.createElement('div');
        toast.className = 'toast-message';
        toast.style.background = '<?= $_SESSION['flash']['color'] ?>';
        toast.innerText = '<?= addslashes($_SESSION['flash']['message']) ?>';
        document.body.appendChild(toast);
        setTimeout(() => toast.remove(), 4000);
        <?php unset($_SESSION['flash']); ?>
    <?php endif; ?>
});

// Print Invoice Function
function printInvoice(){
    let content = document.getElementById('invoiceTable').outerHTML;
    let win = window.open('', '', 'height=700,width=900');
    win.document.write('<html><head><title>Invoice</title>');
    win.document.write('<style>table{width:100%;border-collapse:collapse;} th, td{border:1px solid #000;padding:6px;text-align:left;} th{background:#f0f0f0;} .table-success{background:#d4edda;} .table-danger{background:#f8d7da;}</style>');
    win.document.write('</head><body>');
    win.document.write('<h3>Invoice for Patient: <?= htmlspecialchars($patient['first_name'].' '.$patient['last_name']) ?> — Visit #: <?= $visit_id ?></h3>');
    win.document.write(content);
    win.document.write('</body></html>');
    win.document.close();
    win.print();
}
</script>

<style>
.toast-message { position: fixed; top: 20px; right: 20px; padding: 8px 15px; color: #fff; border-radius: 5px; z-index: 9999; font-size: 13px; }
.table-sm td, .table-sm th { padding: .25rem; }
.card-body { padding: .5rem; }
.badge { border-radius: 6px; padding: 4px 8px; font-size: 13px; }
.table-success { background-color: #d4edda !important; }
.table-danger { background-color: #f8d7da !important; }
</style>