<?php
session_start();
if (!isset($_SESSION['username']) || ($_SESSION['role'] ?? '') !== 'cashier') {
    header("Location: login.php");
    exit();
}

require 'db_connect.php';

// 🔹 Make sure we have an open cash session so we can attach payments to it
include 'require_cash_session.php';

date_default_timezone_set('Africa/Nairobi');

$username     = $_SESSION['username'] ?? 'User';
$cashSessionId = $_SESSION['cash_session_id'] ?? null;

$page_title = "Record Credit Payment | Cashier POS";
$active     = 'debts'; // highlight Credit Sales (debts) in top nav

// Ensure we have a debt id
if (!isset($_GET['id'])) {
    die("No credit sale selected.");
}

$debt_id = intval($_GET['id']);
if ($debt_id <= 0) {
    die("Invalid credit sale id.");
}

// Helper: generate receipt id consistent with sales page
function generateReceiptID() {
    return 'RCP-' . date('ymd-His') . '-' . rand(1000,9999);
}

/* -----------------------------------------
   FETCH CREDIT SALE (DEBT)
-------------------------------------------*/
$debtQuery = $conn->query("
    SELECT d.*,
           p.name          AS product_name,
           p.selling_price AS original_selling_price,
           p.buying_price  AS original_buying_price
    FROM customer_debts d
    LEFT JOIN products p ON d.product_id = p.id
    WHERE d.id = $debt_id
");
$debt = $debtQuery ? $debtQuery->fetch_assoc() : null;

if (!$debt) {
    die("Credit sale not found.");
}

/* -----------------------------------------
   FETCH PAYMENT HISTORY + TOTAL PAID
-------------------------------------------*/
$payments = $conn->query("
    SELECT *
    FROM debt_payments
    WHERE debt_id = $debt_id
    ORDER BY payment_date ASC
");

$total_paid = 0.0;
if ($payments && $payments->num_rows > 0) {
    while ($p = $payments->fetch_assoc()) {
        $total_paid += (float)$p['amount_paid'];
    }
    // reset pointer for later display
    $payments->data_seek(0);
}

$remaining = (float)$debt['amount'] - $total_paid;
if ($remaining < 0) $remaining = 0.0;

$message = "";

/* -----------------------------------------
   PROCESS PAYMENT
-------------------------------------------*/
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['pay'])) {
    $amount         = (float)($_POST['amount'] ?? 0);
    $payment_method = $_POST['payment_method'] ?? 'cash';
    $cashier        = $username;
    $payment_date   = date("Y-m-d H:i:s");

    // basic sanitization for method
    $valid_methods = ['cash','mpesa','bank'];
    if (!in_array($payment_method, $valid_methods, true)) {
        $payment_method = 'cash';
    }

    if ($amount <= 0) {
        $message = "<div class='alert alert-error'>Invalid amount entered.</div>";
    } elseif ($amount > $remaining) {
        $message = "<div class='alert alert-error'>Amount exceeds remaining balance (KES " .
                    number_format($remaining,2) . ").</div>";
    } else {

        // 1) Record payment in debt_payments (with method)
        $stmt = $conn->prepare("
            INSERT INTO debt_payments (debt_id, amount_paid, payment_date, cashier, payment_method)
            VALUES (?, ?, ?, ?, ?)
        ");
        if ($stmt) {
            $stmt->bind_param("idsss", $debt_id, $amount, $payment_date, $cashier, $payment_method);
            $stmt->execute();
            $stmt->close();
        }

        // 2) Recalculate totals
        $total_paid += $amount;
        $remaining   = (float)$debt['amount'] - $total_paid;
        if ($remaining < 0) $remaining = 0.0;

        $isFullyPaid = ($remaining <= 0.00001);

        // 3) Generate a receipt ID for this payment (and final sale if fully paid)
        $receipt_id = generateReceiptID();

        // 4) Record this payment into payments table so it shows in close cash session
        if ($cashSessionId) {
            // NOTE: adjust column names if your payments table differs
            $pstmt = $conn->prepare("
                INSERT INTO payments (
                    receipt_id,
                    amount_due,
                    paid_at,
                    change_amount,
                    payment_method,
                    cash_session_id,
                    is_credit
                ) VALUES (?, ?, ?, 0, ?, ?, 1)
            ");
            if ($pstmt) {
                // amount_due = amount (partial or full), paid_at = amount
                $pstmt->bind_param("sddsi", $receipt_id, $amount, $amount, $payment_method, $cashSessionId);
                $pstmt->execute();
                $pstmt->close();
            }
        }

        // 5) If fully paid, push this credit sale into sales table as a normal sale with sale_type='credit'
        if ($isFullyPaid) {
            $qty       = (int)$debt['quantity'];
            $orig_sell = (float)$debt['original_selling_price'];
            $buy_price = (float)$debt['original_buying_price'];

            // Price customer actually paid per unit
            $discounted_price = $qty > 0 ? ((float)$debt['amount'] / $qty) : 0;
            $unit_discount    = $orig_sell - $discounted_price;
            $total_discount   = $unit_discount * $qty;
            $total_sale       = $discounted_price * $qty;
            $profit           = ($discounted_price - $buy_price) * $qty;

            // Insert into sales (note sale_type='credit')
            $pid = (int)$debt['product_id'];

            $stmt2 = $conn->prepare("
                INSERT INTO sales (
                    receipt_id,
                    sale_datetime,
                    cashier,
                    product_id,
                    quantity,
                    buying_price,
                    selling_price,
                    discount,
                    total_sale,
                    profit,
                    sale_type,
                    refunded
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'credit', 0)
            ");
            if ($stmt2) {
                $stmt2->bind_param(
                    "sssiddiddd",
                    $receipt_id,
                    $payment_date,
                    $cashier,
                    $pid,
                    $qty,
                    $buy_price,
                    $discounted_price,
                    $total_discount,
                    $total_sale,
                    $profit
                );
                $stmt2->execute();
                $stmt2->close();
            }

            // Instead of deleting the credit sale, mark it as fully paid,
            // so you can later show it on a "Credit Paid" page.
            $conn->query("
                UPDATE customer_debts
                SET status = 'Fully Paid'
                WHERE id = {$debt_id}
            ");

            header("Location: customer_debts.php?paid=1");
            exit();

        } else {
            // 6) Partially paid
            $conn->query("
                UPDATE customer_debts
                SET status = 'Partially Paid'
                WHERE id = {$debt_id}
            ");

            header("Location: cashier_record_debt_payments.php?id={$debt_id}&success=1");
            exit();
        }
    }

    // Re-fetch payment history for display after any error
    $payments = $conn->query("
        SELECT *
        FROM debt_payments
        WHERE debt_id = $debt_id
        ORDER BY payment_date ASC
    ");
}

/* Status badge */
if ($total_paid == 0) {
    $status_label = "Not paid";
    $badge_class  = "badge-unpaid";
} elseif ($remaining > 0) {
    $status_label = "Partially paid";
    $badge_class  = "badge-partial";
} else {
    $status_label = "Fully paid";
    $badge_class  = "badge-paid";
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <?php include 'cashier_head.php'; ?>
    <style>
        /* Layout for footer at bottom */
        html, body {
            height: 100%;
        }
        body {
            min-height: 100vh;
            display: flex;
            flex-direction: column;
        }
        .cashier-shell {
            flex: 1;
            display: flex;
        }

        .cashier-main {
            padding: 24px 30px 34px;
        }

        @media (max-width: 960px) {
            .cashier-main {
                padding: 18px 16px 26px;
            }
        }

        .pay-layout {
            max-width: 1100px;
            margin: 0 auto;
            display: grid;
            grid-template-columns: minmax(0, 1.3fr) minmax(0, 1fr);
            gap: 18px;
        }

        @media (max-width: 960px) {
            .pay-layout {
                grid-template-columns: minmax(0,1fr);
            }
        }

        .pos-card,
        .pos-table-card {
            background: linear-gradient(135deg, #064ab8 0%, #022a6b 55%, #021d53 100%);
            border-radius: 18px;
            padding: 18px 22px 20px;
            box-shadow: 0 20px 45px rgba(0,0,0,0.55);
            color: #E9F5FF;
            border: 1px solid rgba(130,238,253,0.5);
            margin-bottom: 22px;
        }

        html[data-theme="light"] .pos-card,
        html[data-theme="light"] .pos-table-card {
            background: #ffffff;
            border-color: rgba(148,163,184,0.55);
            color: #0f172a;
            box-shadow: 0 12px 26px rgba(15,23,42,0.12);
        }

        .pos-card-header h2 {
            font-size: 18px;
            font-weight: 600;
        }

        .pos-card-header p {
            font-size: 13px;
            color: #c3d8ff;
            margin-top: 3px;
        }

        html[data-theme="light"] .pos-card-header p {
            color: #4b5563;
        }

        .info-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
            gap: 10px;
            margin-top: 10px;
        }

        .info-item {
            background: rgba(0,26,80,0.75);
            border-radius: 12px;
            padding: 8px 10px;
            font-size: 12px;
            border: 1px solid rgba(148,163,184,0.35);
        }

        .info-label {
            color: #9CA3AF;
            font-size: 11px;
            text-transform: uppercase;
            letter-spacing: 0.06em;
            margin-bottom: 3px;
        }

        .info-value {
            font-size: 13px;
            font-weight: 500;
        }

        html[data-theme="light"] .info-item {
            background: #f9fafb;
            border-color: rgba(148,163,184,0.40);
            color: #0f172a;
        }

        html[data-theme="light"] .info-label {
            color: #6b7280;
        }

        /* Status badges */
        .badge-unpaid,
        .badge-partial,
        .badge-paid {
            display: inline-flex;
            align-items: center;
            padding: 3px 10px;
            border-radius: 999px;
            font-size: 11px;
            font-weight: 500;
        }

        .badge-unpaid {
            background: rgba(239,68,68,0.12);
            color: #fecaca;
            border: 1px solid rgba(248,113,113,0.7);
        }

        .badge-partial {
            background: rgba(234,179,8,0.12);
            color: #facc15;
            border: 1px solid rgba(250,204,21,0.7);
        }

        .badge-paid {
            background: rgba(34,197,94,0.14);
            color: #bbf7d0;
            border: 1px solid rgba(34,197,94,0.8);
        }

        html[data-theme="light"] .badge-unpaid {
            background: #fee2e2;
            color: #b91c1c;
            border-color: #f87171;
        }
        html[data-theme="light"] .badge-partial {
            background: #fef3c7;
            color: #92400e;
            border-color: #facc15;
        }
        html[data-theme="light"] .badge-paid {
            background: #dcfce7;
            color: #166534;
            border-color: #22c55e;
        }

        /* Alerts */
        .alert {
            margin-top: 10px;
            margin-bottom: 8px;
            padding: 8px 10px;
            border-radius: 10px;
            font-size: 13px;
            border-left-width: 4px;
            border-left-style: solid;
        }

        .alert-success {
            background: rgba(34,197,94,0.12);
            border-left-color: rgba(34,197,94,0.9);
            color: #bbf7d0;
        }

        .alert-error {
            background: rgba(239,68,68,0.14);
            border-left-color: rgba(248,113,113,0.95);
            color: #fecaca;
        }

        html[data-theme="light"] .alert-success {
            background: #dcfce7;
            border-left-color: #16a34a;
            color: #166534;
        }

        html[data-theme="light"] .alert-error {
            background: #fee2e2;
            border-left-color: #ef4444;
            color: #b91c1c;
        }

        /* Payment form */
        .pay-form label {
            font-size: 13px;
            margin-bottom: 4px;
            display: block;
            color: #E9F5FF;
        }

        html[data-theme="light"] .pay-form label {
            color: #0f172a;
        }

        .pay-form input[type="number"],
        .pay-form select {
            width: 100%;
            padding: 9px 11px;
            border-radius: 10px;
            border: 1px solid rgba(130,238,253,0.5);
            background: #0a3d87;
            color: #E9F5FF;
            font-size: 13px;
            margin-bottom: 8px;
        }

        .pay-form input[type="number"]::placeholder {
            color: rgba(226,232,240,0.7);
        }

        .pay-form input[type="number"]:focus,
        .pay-form select:focus {
            outline: none;
            border-color: #00FFE5;
            box-shadow: 0 0 0 1px rgba(0,255,229,0.35);
        }

        html[data-theme="light"] .pay-form input[type="number"],
        html[data-theme="light"] .pay-form select {
            background: #ffffff;
            border-color: rgba(148,163,184,0.55);
            color: #0f172a;
        }

        html[data-theme="light"] .pay-form input[type="number"]::placeholder {
            color: #9ca3af;
        }

        .btn-primary {
            margin-top: 10px;
            padding: 9px 16px;
            border-radius: 999px;
            border: none;
            cursor: pointer;
            font-size: 13px;
            font-weight: 600;
            background: #00FFE5;
            color: #011b35;
            width: 100%;
        }

        .btn-primary:hover {
            filter: brightness(1.08);
        }

        .back-link {
            text-decoration: none;
            font-size: 13px;
            color: #82EEFD;
        }

        .back-link:hover {
            text-decoration: underline;
        }

        html[data-theme="light"] .back-link {
            color: #0369a1;
        }

        /* Payment history table */
        .pos-table-card h3 {
            font-size: 16px;
            font-weight: 600;
            margin-bottom: 6px;
        }

        .pos-table-card p {
            font-size: 12px;
            color: #c3d8ff;
        }

        html[data-theme="light"] .pos-table-card p {
            color: #4b5563;
        }

        .pos-table-wrapper {
            width: 100%;
            overflow-x: auto;
            margin-top: 10px;
        }

        table.pos-table {
            width: 100%;
            border-collapse: collapse;
            font-size: 13px;
            min-width: 500px;
        }

        .pos-table th,
        .pos-table td {
            padding: 8px 8px;
            text-align: center;
            border-bottom: 1px solid rgba(148,163,184,0.25);
            color: #F9FAFF;
        }

        .pos-table th {
            background: #012a73;
            position: sticky;
            top: 0;
            z-index: 1;
            font-weight: 600;
        }

        .pos-table tbody tr:nth-child(even) { background: rgba(2,35,98,0.82); }
        .pos-table tbody tr:nth-child(odd)  { background: rgba(1,26,80,0.82); }
        .pos-table tbody tr:hover { background: rgba(130,238,253,0.16); }

        /* Light theme table overrides */
        html[data-theme="light"] .pos-table th,
        html[data-theme="light"] .pos-table td {
            color: #0f172a;
            border-bottom-color: rgba(148,163,184,0.35);
        }
        html[data-theme="light"] .pos-table th {
            background: #e5f3ff;
        }
        html[data-theme="light"] .pos-table tbody tr:nth-child(even),
        html[data-theme="light"] .pos-table tbody tr:nth-child(odd) {
            background: #f9fafb;
        }

        /* Footer pinned bottom */
        footer {
            background: transparent;
            text-align: center;
            font-size: 12px;
            color: var(--cash-text-muted);
            padding: 10px 18px;
            margin-top: auto;
        }
    </style>
</head>
<body>

<div class="cashier-shell">
    <?php include 'cashier_sidebar.php'; ?>

    <main class="cashier-main">

        <!-- Topbar with nav + theme toggle + sidebar toggle -->
        <div class="cashier-topbar">
            <div class="cashier-topbar-left">
                <h1><?= htmlspecialchars($page_title) ?></h1>
                <small>Update this customer’s credit balance and keep your books in sync.</small>
            </div>

            <div class="cashier-topbar-right">
                <nav class="cashier-topnav">
                    <a href="cashier_dashboard.php" class="<?= ($active === 'dashboard') ? 'active' : '' ?>">Dashboard</a>
                    <a href="record_sales.php" class="<?= ($active === 'sales') ? 'active' : '' ?>">Sales</a>
                    <a href="cashier_view_daily_sales.php" class="<?= ($active === 'daily_sales') ? 'active' : '' ?>">Today’s Sales</a>
                    <a href="transaction_history.php" class="<?= ($active === 'transactions') ? 'active' : '' ?>">Transactions</a>
                    <a href="customers.php" class="<?= ($active === 'customers') ? 'active' : '' ?>">Customers</a>
                    <a href="add_expense.php" class="<?= ($active === 'expenses') ? 'active' : '' ?>">Expenses</a>
                    <a href="customer_debts.php" class="<?= ($active === 'debts') ? 'active' : '' ?>">Credit sales</a>
                </nav>

                <button type="button" class="cashier-theme-toggle" onclick="toggleCashierTheme()">
                    <span class="icon">🌓</span>
                    <span class="label">Theme</span>
                </button>

                <button class="cashier-toggle" type="button" onclick="toggleCashierSidebar()">
                    ☰
                </button>
            </div>
        </div>

        <div class="pay-layout">

            <!-- Left: credit sale info + payment form -->
            <section class="pos-card">
                <div class="pos-card-header">
                    <h2>Credit sale overview</h2>
                    <p>Review the customer’s details and apply a payment to this credit sale.</p>
                </div>

                <?php if (isset($_GET['success'])): ?>
                    <div class="alert alert-success">Payment recorded successfully.</div>
                <?php endif; ?>

                <?php if (!empty($message)): ?>
                    <?= $message ?>
                <?php endif; ?>

                <div class="info-grid">
                    <div class="info-item">
                        <div class="info-label">Customer</div>
                        <div class="info-value"><?= htmlspecialchars($debt['customer_name']) ?></div>
                    </div>
                    <div class="info-item">
                        <div class="info-label">Phone</div>
                        <div class="info-value"><?= htmlspecialchars($debt['phone']) ?></div>
                    </div>
                    <div class="info-item">
                        <div class="info-label">Product</div>
                        <div class="info-value"><?= htmlspecialchars($debt['product_name']) ?></div>
                    </div>
                    <div class="info-item">
                        <div class="info-label">Quantity</div>
                        <div class="info-value"><?= (int)$debt['quantity'] ?></div>
                    </div>
                    <div class="info-item">
                        <div class="info-label">Original total</div>
                        <div class="info-value">KES <?= number_format((float)$debt['amount'], 2) ?></div>
                    </div>
                    <div class="info-item">
                        <div class="info-label">Total paid</div>
                        <div class="info-value">KES <?= number_format($total_paid, 2) ?></div>
                    </div>
                    <div class="info-item">
                        <div class="info-label">Remaining</div>
                        <div class="info-value">KES <?= number_format($remaining, 2) ?></div>
                    </div>
                    <div class="info-item">
                        <div class="info-label">Status</div>
                        <div class="info-value">
                            <span class="<?= $badge_class ?>"><?= $status_label ?></span>
                        </div>
                    </div>
                </div>

                <hr style="border-color: rgba(148,163,184,0.3); margin: 14px 0;">

                <?php if ($remaining > 0): ?>
                    <form method="POST" class="pay-form">
                        <label for="amount">Amount to pay (KES)</label>
                        <input type="number"
                               id="amount"
                               name="amount"
                               step="0.01"
                               min="0.01"
                               max="<?= htmlspecialchars($remaining, ENT_QUOTES) ?>"
                               placeholder="Enter amount e.g. 500.00"
                               required>

                        <label for="payment_method">Payment method</label>
                        <select id="payment_method" name="payment_method" required>
                            <option value="cash">Cash</option>
                            <option value="mpesa">M-Pesa</option>
                            <option value="bank">Bank</option>
                        </select>

                        <button type="submit" name="pay" class="btn-primary">
                            Submit payment
                        </button>
                    </form>
                <?php else: ?>
                    <div class="alert alert-success" style="margin-top: 6px;">
                        This credit sale is fully paid and has been recorded in sales as a credit sale.
                    </div>
                <?php endif; ?>

                <div style="margin-top: 14px;">
                    <a href="customer_debts.php" class="back-link">← Back to credit sales</a>
                </div>
            </section>

            <!-- Right: payment history -->
            <section class="pos-table-card">
                <h3>Credit payment history</h3>
                <p>Track how this customer has been clearing their credit balance over time.</p>

                <div class="pos-table-wrapper">
                    <table class="pos-table">
                        <thead>
                            <tr>
                                <th>#</th>
                                <th>Amount paid (KES)</th>
                                <th>Payment method</th>
                                <th>Payment date</th>
                                <th>Cashier</th>
                            </tr>
                        </thead>
                        <tbody>
                        <?php if ($payments && $payments->num_rows > 0): ?>
                            <?php $i = 1; while ($row = $payments->fetch_assoc()): ?>
                                <tr>
                                    <td><?= $i++ ?></td>
                                    <td><?= number_format((float)$row['amount_paid'], 2) ?></td>
                                    <td><?= htmlspecialchars($row['payment_method'] ?? 'cash') ?></td>
                                    <td><?= htmlspecialchars($row['payment_date']) ?></td>
                                    <td><?= htmlspecialchars($row['cashier']) ?></td>
                                </tr>
                            <?php endwhile; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="5" style="padding:16px; color:#c3d8ff;">
                                    No payments recorded yet for this credit sale.
                                </td>
                            </tr>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </section>

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

<?php include 'footer.php'; ?>

<script>
function toggleCashierSidebar() {
    const sidebar = document.getElementById('cashierSidebar');
    if (sidebar) {
        sidebar.classList.toggle('is-collapsed');
    }
}
</script>

</body>
</html>
