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

require 'db_connect.php';

// GET DEBT ID
if (!isset($_GET['id'])) {
    die("No debt selected");
}

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

// Fetch debt
$debt = $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
")->fetch_assoc();

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

// Fetch payment history
$payments = $conn->query("
    SELECT * FROM debt_payments
    WHERE debt_id = $debt_id
    ORDER BY payment_date ASC
");

// Calculate total paid
$total_paid = 0;
while ($p = $payments->fetch_assoc()) {
    $total_paid += $p['amount_paid'];
}
$payments->data_seek(0); // reset pointer

$remaining = $debt['amount'] - $total_paid;
$message = "";

/* -----------------------------------------
   PROCESS PAYMENT
-------------------------------------------*/
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['pay'])) {

    $amount       = floatval($_POST['amount']);
    $cashier      = $_SESSION['username'];
    $payment_date = date("Y-m-d H:i:s");

    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 {

        // INSERT PAYMENT
        $stmt = $conn->prepare("
            INSERT INTO debt_payments (debt_id, amount_paid, payment_date, cashier)
            VALUES (?, ?, ?, ?)
        ");
        $stmt->bind_param("idss", $debt_id, $amount, $payment_date, $cashier);
        $stmt->execute();
        $stmt->close();

        // Recalculate totals
        $total_paid += $amount;
        $remaining = $debt['amount'] - $total_paid;

        // Calculate discount per unit and total
        $unit_discount   = $debt['original_selling_price'] - ($debt['amount'] / $debt['quantity']);
        $total_discount  = $unit_discount * $debt['quantity'];
        $total_sale      = $debt['amount']; // total after discount

        // If fully paid, insert into sales, update stock, delete debt
        if ($remaining <= 0) {

            // Update product stock
            $product = $conn->query("SELECT * FROM products WHERE id = {$debt['product_id']}")->fetch_assoc();
            if ($product) {
                $new_stock = $product['quantity'] - $debt['quantity'];
                $conn->query("UPDATE products SET quantity = $new_stock WHERE id = {$debt['product_id']}");
            }

            // Insert into sales table
            $stmt2 = $conn->prepare("
                INSERT INTO sales (product_id, quantity, selling_price, buying_price, discount, total_sale, sale_datetime, cashier)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?)
            ");
            $stmt2->bind_param(
                "iiddddss",
                $debt['product_id'],
                $debt['quantity'],
                $debt['original_selling_price'],
                $debt['original_buying_price'],
                $total_discount,
                $total_sale,
                $payment_date,
                $cashier
            );
            $stmt2->execute();
            $stmt2->close();

            // Delete debt
            $conn->query("DELETE FROM customer_debts WHERE id = $debt_id");

            header("Location: customer_debts.php?success=1");
            exit();
        } else {
            // Partially paid: update debt status
            $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 updated payments
$payments = $conn->query("
    SELECT * FROM debt_payments
    WHERE debt_id = $debt_id
    ORDER BY payment_date ASC
");

// optional title for head.php
$page_title = "Record Debt Payment";
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <title><?= htmlspecialchars($page_title) ?></title>
    <?php include('head.php'); ?>

    <style>
        /* THEME VARIABLES */
        body:not([data-theme="light"]) {
            --bg-main: #001f3f;
            --bg-card: #012a57;
            --text-main: #F9FAFB;
            --text-muted: #9CA3AF;
            --accent: #00ffef;
            --border-soft: rgba(130,238,253,0.45);
            --status-danger: #f97373;
            --status-warning: #facc15;
            --status-success: #4ade80;
        }

        body[data-theme="light"] {
            --bg-main: #f3f4f6;
            --bg-card: #ffffff;
            --text-main: #111827;
            --text-muted: #6b7280;
            --accent: #0ea5e9;
            --border-soft: rgba(148,163,184,0.6);
            --status-danger: #dc2626;
            --status-warning: #eab308;
            --status-success: #16a34a;
        }

        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 beside sidebar */
        .content-area {
            margin-left: 260px;
            padding: 25px 30px 40px;
            min-height: 100vh;
            background:
                radial-gradient(circle at top left, rgba(56,189,248,0.14), transparent 55%),
                var(--bg-main);
            transition: margin-left 0.3s ease, background 0.3s ease;
        }
        @media (max-width: 768px) {
            .content-area {
                margin-left: 80px;
                padding: 20px;
            }
        }

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

        /* PAGE HEADER */
        .page-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-end;
            flex-wrap: wrap;
            gap: 10px;
            margin-bottom: 20px;
        }

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

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

        /* LAYOUT */
        .layout-grid {
            display: grid;
            grid-template-columns: minmax(0, 0.9fr) minmax(0, 1.1fr);
            gap: 18px;
            align-items: flex-start;
        }

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

        .card-box {
            background: var(--bg-card);
            border-radius: 16px;
            padding: 18px 20px;
            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 28px rgba(15,23,42,0.10);
        }

        .card-title {
            font-size: 16px;
            font-weight: 600;
            margin-bottom: 10px;
        }

        .card-section {
            margin-bottom: 14px;
        }

        .summary-row {
            font-size: 14px;
            margin-bottom: 4px;
        }

        .summary-label {
            font-weight: 500;
            color: var(--text-muted);
        }

        .summary-value {
            font-weight: 600;
        }

        /* STATUS BADGE */
        .status-badge {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            padding: 3px 10px;
            font-size: 11px;
            border-radius: 999px;
            font-weight: 600;
            letter-spacing: 0.04em;
            text-transform: uppercase;
        }
        .status-danger {
            background: rgba(248,113,113,0.15);
            color: var(--status-danger);
            border: 1px solid rgba(248,113,113,0.55);
        }
        .status-warning {
            background: rgba(250,204,21,0.15);
            color: var(--status-warning);
            border: 1px solid rgba(250,204,21,0.55);
        }
        .status-success {
            background: rgba(74,222,128,0.15);
            color: var(--status-success);
            border: 1px solid rgba(74,222,128,0.55);
        }

        /* ALERTS */
        .alert {
            padding: 10px 12px;
            border-radius: 8px;
            margin-bottom: 12px;
            font-size: 13px;
        }
        .alert-success {
            background: rgba(34,197,94,0.18);
            border-left: 4px solid #22c55e;
            color: #bbf7d0;
        }
        .alert-error {
            background: rgba(239,68,68,0.18);
            border-left: 4px solid #ef4444;
            color: #fecaca;
        }
        body[data-theme="light"] .alert-success {
            color: #166534;
        }
        body[data-theme="light"] .alert-error {
            color: #b91c1c;
        }

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

        .form-control-custom {
            width: 100%;
            padding: 9px 10px;
            border-radius: 8px;
            border: 1px solid var(--border-soft);
            background: #02152e;
            color: #f9fafb;
            font-size: 14px;
            outline: none;
            transition: border-color 0.15s ease-out, box-shadow 0.15s ease-out, background 0.15s ease-out;
        }

        .form-control-custom::placeholder {
            color: #9ca3af;
        }

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

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

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

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

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

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

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

        /* TABLE */
        .table-wrapper {
            width: 100%;
            margin-top: 8px;
            overflow-x: auto;
        }

        table {
            width: 100%;
            min-width: 600px;
            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: #01356f;
        }
        body[data-theme="light"] thead tr {
            background: #e0f2fe;
        }

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

        th {
            font-weight: 600;
            color: #f9fafb;
        }
        body[data-theme="light"] th {
            color: #111827;
        }

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

        body[data-theme="light"] tbody tr {
            background: #ffffff;
        }
        body[data-theme="light"] tbody tr:nth-child(even) {
            background: #f9fafb;
        }
        body[data-theme="light"] tbody tr:hover {
            background: #e5f3ff;
        }

        .numeric {
            text-align: right;
        }

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

<body data-theme="dark">

<?php include("sidebar.php"); ?>
<?php include("topbar.php"); ?>

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

    <div class="page-header">
        <div>
            <div class="page-title">Record Debt Payment</div>
            <div class="page-subtitle">
                Manage payments for <?= htmlspecialchars($debt['customer_name']) ?> · Debt #<?= $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;
    }
    ?>

    <?php
    // Determine status + class
    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";
    }
    ?>

    <div class="layout-grid">

        <!-- LEFT: Summary + payment form -->
        <div class="card-box">
            <div class="card-title">Debt Summary</div>

            <div class="card-section">
                <div class="summary-row">
                    <span class="summary-label">Customer:</span>
                    <span class="summary-value"> <?= htmlspecialchars($debt['customer_name']) ?></span>
                </div>
                <div class="summary-row">
                    <span class="summary-label">Phone:</span>
                    <span class="summary-value"> <?= htmlspecialchars($debt['phone']) ?></span>
                </div>
                <div class="summary-row">
                    <span class="summary-label">Product:</span>
                    <span class="summary-value"> <?= htmlspecialchars($debt['product_name']) ?></span>
                </div>
                <div class="summary-row">
                    <span class="summary-label">Quantity:</span>
                    <span class="summary-value"> <?= (int)$debt['quantity'] ?></span>
                </div>
                <div class="summary-row">
                    <span class="summary-label">Total Amount:</span>
                    <span class="summary-value"> KES <?= number_format($debt['amount'],2) ?></span>
                </div>
                <div class="summary-row">
                    <span class="summary-label">Total Paid:</span>
                    <span class="summary-value"> KES <?= number_format($total_paid,2) ?></span>
                </div>
                <div class="summary-row">
                    <span class="summary-label">Remaining:</span>
                    <span class="summary-value"> KES <?= number_format($remaining,2) ?></span>
                </div>
                <div class="summary-row" style="margin-top:6px;">
                    <span class="summary-label">Status:</span>
                    <span class="<?= $status_class ?>"><?= $status_label ?></span>
                </div>
            </div>

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

            <?php if ($remaining > 0): ?>
                <div class="card-title" style="font-size:15px; margin-bottom:6px;">Make Payment</div>
                <form method="POST">
                    <label for="amount">Amount (KES)</label>
                    <input 
                        type="number" 
                        step="0.01" 
                        name="amount" 
                        id="amount" 
                        class="form-control-custom" 
                        placeholder="Enter payment amount" 
                        required
                    >
                    <button class="btn-primary-custom" name="pay">Submit Payment</button>
                </form>
            <?php else: ?>
                <div class="alert alert-success">This debt is fully paid.</div>
            <?php endif; ?>

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

        <!-- RIGHT: Payment history -->
        <div class="card-box">
            <div class="card-title">Payment History</div>

            <div class="table-wrapper">
                <table>
                    <thead>
                        <tr>
                            <th>#</th>
                            <th>Amount Paid (KES)</th>
                            <th>Payment Date</th>
                            <th>Cashier</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php $i = 1; while($row = $payments->fetch_assoc()): ?>
                        <tr>
                            <td><?= $i++ ?></td>
                            <td class="numeric"><?= number_format($row['amount_paid'],2) ?></td>
                            <td><?= htmlspecialchars($row['payment_date']) ?></td>
                            <td><?= htmlspecialchars($row['cashier']) ?></td>
                        </tr>
                        <?php endwhile; ?>
                        <?php if ($i === 1): ?>
                        <tr>
                            <td colspan="4">No payments recorded yet.</td>
                        </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

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

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

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

<script>
// initialize theme from localStorage on load
(function () {
    const saved = localStorage.getItem('adminTheme');
    const theme = (saved === 'light' || saved === 'dark') ? saved : 'dark';
    document.body.setAttribute('data-theme', theme);
})();

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>
