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

require 'db_connect.php';

$page_title = "Record Credit Payment (Admin)";

// ----------------------
// Helpers
// ----------------------
function generateReceiptID() {
    return 'RCP-' . date('ymd-His') . '-' . rand(1000, 9999);
}

// ----------------------
// Get debt
// ----------------------
if (!isset($_GET['id'])) {
    die("No credit sale selected.");
}

$debt_id = (int)$_GET['id'];

$debtStmt = $conn->prepare("
    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 = ?
");
$debtStmt->bind_param("i", $debt_id);
$debtStmt->execute();
$debt = $debtStmt->get_result()->fetch_assoc();
$debtStmt->close();

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

// total already paid
$totalPaidRow = $conn->query("
    SELECT COALESCE(SUM(amount_paid),0) AS total_paid
    FROM debt_payments
    WHERE debt_id = {$debt_id}
")->fetch_assoc();
$total_paid = (float)($totalPaidRow['total_paid'] ?? 0);

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

$message = "";

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

    $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.</div>";
    } elseif ($amount > $remaining) {
        $message = "<div class='alert alert-error'>Amount exceeds remaining balance!</div>";
    } else {
        // fresh remaining (safety)
        $totalPaidRow = $conn->query("
            SELECT COALESCE(SUM(amount_paid),0) AS total_paid
            FROM debt_payments
            WHERE debt_id = {$debt_id}
        ")->fetch_assoc();
        $total_paid = (float)($totalPaidRow['total_paid'] ?? 0);
        $remaining  = (float)$debt['amount'] - $total_paid;
        if ($remaining < 0) $remaining = 0.0;

        if ($amount > $remaining + 0.00001) {
            $message = "<div class='alert alert-error'>Amount exceeds remaining balance!</div>";
        } else {
            // create receipt ID for this payment
            $receipt_id = generateReceiptID();

            // insert into debt_payments
            $stmt = $conn->prepare("
                INSERT INTO debt_payments 
                    (debt_id, receipt_id, amount_paid, payment_date, cashier, discount, payment_method, cash_session_id)
                VALUES (?, ?, ?, ?, ?, 0, ?, NULL)
            ");
            if ($stmt) {
                $stmt->bind_param(
                    "isdsss",
                    $debt_id,
                    $receipt_id,
                    $amount,
                    $payment_date,
                    $cashier,
                    $payment_method
                );
                $stmt->execute();
                $stmt->close();
            }

            // recompute totals after insert
            $totalPaidRow = $conn->query("
                SELECT COALESCE(SUM(amount_paid),0) AS total_paid
                FROM debt_payments
                WHERE debt_id = {$debt_id}
            ")->fetch_assoc();
            $total_paid = (float)($totalPaidRow['total_paid'] ?? 0);
            $remaining  = (float)$debt['amount'] - $total_paid;
            if ($remaining < 0) $remaining = 0.0;

            $isFullyPaid = ($remaining <= 0.00001);

            // if fully paid -> mark debt & insert into sales as credit sale
            if ($isFullyPaid) {
                $qty       = (int)$debt['quantity'];
                $orig_sell = (float)$debt['original_selling_price'];
                $buy_price = (float)$debt['original_buying_price'];

                // actual price the customer pays 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;

                $pid = (int)$debt['product_id'];

                // IMPORTANT: do NOT update stock here – it was already reduced when the credit sale was created.

                // record final sale (sale_type = credit)
                $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();
                }

                // mark credit as fully paid (keep record for history)
                $conn->query("
                    UPDATE customer_debts
                    SET status = 'Fully Paid'
                    WHERE id = {$debt_id}
                ");

                header("Location: admin_customer_debts.php?paid=1");
                exit();
            } else {
                // still outstanding -> mark as partially paid
                $conn->query("
                    UPDATE customer_debts
                    SET status = 'Partially Paid'
                    WHERE id = {$debt_id}
                ");

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

// reload history for display
$paymentsStmt = $conn->prepare("
    SELECT *
    FROM debt_payments
    WHERE debt_id = ?
    ORDER BY payment_date ASC
");
$paymentsStmt->bind_param("i", $debt_id);
$paymentsStmt->execute();
$payments = $paymentsStmt->get_result();

// status badge
if ($total_paid == 0) {
    $status_label = "Not paid";
    $status_class = "status-badge status-danger";
} elseif ($remaining > 0) {
    $status_label = "Partially paid";
    $status_class = "status-badge status-warning";
} else {
    $status_label = "Fully paid";
    $status_class = "status-badge status-success";
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <title><?= htmlspecialchars($page_title) ?></title>
    <?php include('head.php'); ?>

    <style>
        body {
            margin: 0;
            font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
            -webkit-font-smoothing: antialiased;
            background: var(--bg-main);
            color: var(--text-main);
        }

        .content-area {
            margin-left: 260px;
            padding: 24px 30px 36px;
            min-height: 100vh;
            background:
                radial-gradient(circle at top left, rgba(56,189,248,0.12), transparent 55%),
                var(--bg-main);
            transition: margin-left 0.3s ease;
        }

        @media (max-width: 768px) {
            .content-area {
                margin-left: 80px;
                padding: 18px 18px 28px;
            }
        }

        .content-area.collapsed {
            margin-left: 80px;
        }

        .page-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-end;
            flex-wrap: wrap;
            gap: 10px;
            margin-bottom: 18px;
        }

        .page-title {
            font-size: 22px;
            font-weight: 600;
            color: var(--text-heading);
        }

        .page-subtitle {
            font-size: 13px;
            color: var(--text-muted);
            margin-top: 3px;
        }

        /* wider layout so payment history uses more space */
        .layout-grid {
            max-width: 1360px;
            margin: 0 auto;
            display: grid;
            grid-template-columns: minmax(0, 1.05fr) minmax(0, 1.05fr);
            gap: 20px;
        }

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

        .card-box {
            background: var(--bg-card);
            border-radius: 16px;
            padding: 18px 20px 22px;
            border: 1px solid var(--border-soft);
            box-shadow: 0 14px 30px rgba(0,0,0,0.45);
        }

        body[data-theme="light"] .card-box {
            box-shadow: 0 12px 26px rgba(15,23,42,0.08);
        }

        .card-title {
            font-size: 16px;
            font-weight: 600;
            margin-bottom: 6px;
            color: var(--text-heading);
        }

        .card-subtitle {
            font-size: 12px;
            color: var(--text-muted);
            margin-bottom: 10px;
        }

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

        .summary-item {
            font-size: 13px;
        }

        .summary-label {
            color: var(--text-muted);
            font-size: 11px;
            text-transform: uppercase;
            letter-spacing: 0.08em;
        }

        .summary-value {
            font-weight: 600;
            margin-top: 2px;
        }

        .status-badge {
            display: inline-flex;
            align-items: center;
            padding: 3px 10px;
            border-radius: 999px;
            font-size: 11px;
            font-weight: 600;
            letter-spacing: 0.05em;
            text-transform: uppercase;
        }
        .status-danger {
            background: rgba(239,68,68,0.16);
            color: #fecaca;
            border: 1px solid rgba(248,113,113,0.8);
        }
        .status-warning {
            background: rgba(234,179,8,0.16);
            color: #facc15;
            border: 1px solid rgba(250,204,21,0.8);
        }
        .status-success {
            background: rgba(34,197,94,0.16);
            color: #bbf7d0;
            border: 1px solid rgba(34,197,94,0.8);
        }

        /* alerts */
        .alert {
            padding: 9px 11px;
            border-radius: 8px;
            margin-bottom: 10px;
            font-size: 13px;
            border-left: 4px solid transparent;
        }
        .alert-success {
            background: rgba(34,197,94,0.16);
            border-left-color: #22c55e;
            color: #bbf7d0;
        }
        .alert-error {
            background: rgba(239,68,68,0.18);
            border-left-color: #ef4444;
            color: #fecaca;
        }

        /* form */
        label {
            display: block;
            margin-top: 10px;
            margin-bottom: 4px;
            font-size: 13px;
            font-weight: 500;
            color: var(--text-heading);
        }

        .form-control-custom {
            width: 100%;
            padding: 9px 10px;
            border-radius: 10px;
            border: 1px solid var(--border-soft);
            background: var(--bg-table-head);
            color: var(--text-main);
            font-size: 14px;
            outline: none;
        }

        .form-control-custom:focus {
            border-color: var(--accent-gold, #0ea5e9);
            box-shadow: 0 0 0 1px rgba(56,189,248,0.4);
        }

        body[data-theme="light"] .form-control-custom {
            background: #ffffff;
        }

        .btn-primary-custom {
            width: 100%;
            margin-top: 14px;
            padding: 10px;
            border-radius: 999px;
            border: none;
            cursor: pointer;
            font-size: 14px;
            font-weight: 600;
            background: linear-gradient(to right, #22c55e, #0ea5e9);
            color: #001f3f;
        }

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

        .btn-back {
            display: inline-block;
            margin-top: 14px;
            font-size: 13px;
            padding: 8px 14px;
            border-radius: 999px;
            text-decoration: none;
            border: 1px solid var(--border-soft);
            color: var(--text-main);
        }

        .btn-back:hover {
            background: rgba(148,163,184,0.16);
        }

        /* table */
        .table-wrapper {
            margin-top: 8px;
            max-height: 420px;      /* use vertical space nicely */
            overflow-y: auto;
            overflow-x: hidden;     /* no sideways scroll */
        }

        table {
            width: 100%;
            min-width: 100%;        /* fit inside card */
            border-collapse: collapse;
            background: var(--bg-card);
            border-radius: 10px;
            overflow: hidden;
            box-shadow: 0 8px 20px rgba(0,0,0,0.35);
        }

        thead tr {
            background: var(--bg-table-head, #01356f);
        }

        th, td {
            padding: 8px 9px;
            font-size: 13px;
            border-bottom: 1px solid rgba(255,255,255,0.08);
            text-align: center;
            white-space: nowrap;
        }

        th {
            font-weight: 600;
        }

        tbody tr {
            background: var(--bg-table-row, #01356f);
        }
        tbody tr:nth-child(even) {
            background: #003a73;
        }
        tbody tr:hover {
            background: #014b94;
        }

        .numeric {
            text-align: right;
        }

        .badge-method {
            padding: 3px 8px;
            border-radius: 999px;
            font-size: 11px;
            text-transform: uppercase;
            letter-spacing: 0.05em;
        }
        .badge-method.cash {
            background: rgba(59,130,246,0.18);
            color: #bfdbfe;
        }
        .badge-method.mpesa {
            background: rgba(16,185,129,0.2);
            color: #6ee7b7;
        }
        .badge-method.bank {
            background: rgba(234,179,8,0.2);
            color: #facc15;
        }

        footer { background: transparent; }
    </style>
</head>

<body>

<?php include 'sidebar.php'; ?>
<?php include 'topbar.php'; ?>

<div class="content-area" id="main">

    <div class="page-header">
        <div>
            <div class="page-title">Record Credit Payment</div>
            <div class="page-subtitle">
                Manage payments for <?= htmlspecialchars($debt['customer_name']); ?> · Credit #<?= $debt_id; ?>
            </div>
        </div>
    </div>

    <?php
    if (isset($_GET['success'])) {
        echo "<div class='alert alert-success'>Payment recorded successfully.</div>";
    }
    if (!empty($message)) {
        echo $message;
    }
    ?>

    <div class="layout-grid">

        <!-- LEFT: summary + form -->
        <div class="card-box">
            <div class="card-title">Credit sale overview</div>
            <div class="card-subtitle">Review details and apply a payment to this credit sale.</div>

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

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

            <?php if ($remaining > 0): ?>
                <div class="card-title" style="font-size:15px;margin-bottom:4px;">Make payment</div>
                <form method="POST">
                    <label for="amount">Amount (KES)</label>
                    <input
                        type="number"
                        step="0.01"
                        min="0.01"
                        max="<?= htmlspecialchars($remaining, ENT_QUOTES); ?>"
                        name="amount"
                        id="amount"
                        class="form-control-custom"
                        placeholder="Enter amount e.g. 500.00"
                        required
                    >

                    <label for="payment_method">Payment method</label>
                    <select id="payment_method" name="payment_method" class="form-control-custom" 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-custom">
                        Submit payment
                    </button>
                </form>
            <?php else: ?>
                <div class="alert alert-success">This credit sale is fully paid.</div>
            <?php endif; ?>

            <a href="admin_customer_debts.php" class="btn-back">← Back to credit sales</a>
        </div>

        <!-- RIGHT: payment history -->
        <div class="card-box">
            <div class="card-title">Credit payment history</div>
            <div class="card-subtitle">All payments recorded against this credit sale.</div>

            <div class="table-wrapper">
                <table>
                    <thead>
                        <tr>
                            <th>#</th>
                            <th>Receipt #</th>
                            <th>Amount paid (KES)</th>
                            <th>Method</th>
                            <th>Payment date</th>
                            <th>Cashier</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php $i = 1; while ($row = $payments->fetch_assoc()): ?>
                            <?php
                                $method = strtolower($row['payment_method'] ?? 'cash');
                                $badgeMethod = 'badge-method ' . $method;
                            ?>
                            <tr>
                                <td><?= $i++; ?></td>
                                <td><?= htmlspecialchars($row['receipt_id']); ?></td>
                                <td class="numeric"><?= number_format((float)$row['amount_paid'], 2); ?></td>
                                <td>
                                    <span class="<?= $badgeMethod; ?>">
                                        <?= strtoupper(htmlspecialchars($row['payment_method'] ?? 'cash')); ?>
                                    </span>
                                </td>
                                <td><?= htmlspecialchars($row['payment_date']); ?></td>
                                <td><?= htmlspecialchars($row['cashier']); ?></td>
                            </tr>
                        <?php endwhile; ?>
                        <?php if ($i === 1): ?>
                            <tr>
                                <td colspan="6">No payments recorded yet.</td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

    </div><!-- /layout-grid -->

</div><!-- /content-area -->

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

<script>
(function () {
    const saved = localStorage.getItem('adminTheme');
    if (saved === 'light' || saved === 'dark') {
        document.body.setAttribute('data-theme', saved);
    }
})();

function toggleAdminTheme() {
    const current = document.body.getAttribute('data-theme') || 'dark';
    const next = current === 'dark' ? 'light' : 'dark';
    document.body.setAttribute('data-theme', next);
    localStorage.setItem('adminTheme', next);
}

function toggleAdminSidebar() {
    const sidebar = document.getElementById('sidebar');
    const main    = document.getElementById('main');
    if (!sidebar || !main) return;
    sidebar.classList.toggle('collapsed');
    main.classList.toggle('collapsed');
}
</script>

</body>
</html>
