<?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
    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.");
}

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

// Calculate totals
$total_paid = 0;
while ($p = $payments->fetch_assoc()) {
    $total_paid += $p['amount_paid'];  // CORRECT COLUMN
}

// Reset pointer for display
$payments->data_seek(0);

// Calculate remaining
$remaining = $debt['amount'] - $total_paid;

$message = "";

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

    $amount = floatval($_POST['amount']);

    if ($amount <= 0) {
        $message = "<div class='alert alert-danger'>Invalid amount.</div>";
    } elseif ($amount > $remaining) {
        $message = "<div class='alert alert-danger'>Amount exceeds balance!</div>";
    } else {

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

        // INSERT CORRECT COLUMNS
        $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;

        // Update debt status
        if ($remaining <= 0) {
            $conn->query("UPDATE customer_debts SET status='Fully Paid' WHERE id = $debt_id");

            // Register as normal sale
            $conn->query("
                INSERT INTO sales (
                    sale_datetime, cashier, product_id, quantity,
                    buying_price, selling_price, total_sale, profit
                )
                SELECT 
                    NOW(),
                    '$cashier',
                    product_id,
                    quantity,
                    (SELECT buying_price FROM products WHERE id = product_id),
                    (SELECT selling_price FROM products WHERE id = product_id),
                    amount,
                    (SELECT (selling_price - buying_price) * quantity FROM products WHERE id = product_id)
                FROM customer_debts
                WHERE id = $debt_id
            ");
        } else {
            $conn->query("UPDATE customer_debts SET status='Partially Paid' WHERE id = $debt_id");
        }

        header("Location: 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
");
?>

<!DOCTYPE html>
<html>
<head>
    <title>Record Debt Payment</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.1.3/css/bootstrap.min.css" rel="stylesheet">
</head>

<body class="bg-light">

<div class="container mt-4 p-4 bg-white shadow rounded">

    <h3>Record Payment</h3>

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

    <h5>Debt Information</h5>
    <p><strong>Customer:</strong> <?= $debt['customer_name'] ?></p>
    <p><strong>Phone:</strong> <?= $debt['phone'] ?></p>
    <p><strong>Product:</strong> <?= $debt['product_name'] ?></p>
    <p><strong>Qty:</strong> <?= $debt['quantity'] ?></p>
    <p><strong>Total Amount:</strong> KES <?= number_format($debt['amount'], 2) ?></p>
    <p><strong>Total Paid:</strong> KES <?= number_format($total_paid, 2) ?></p>
    <p><strong>Remaining:</strong> KES <?= number_format($remaining, 2) ?></p>

    <?php
if ($total_paid == 0) {
    $status_label = "Not Paid";
    $badge = "danger";
} elseif ($remaining > 0) {
    $status_label = "Partially Paid";
    $badge = "warning";
} else {
    $status_label = "Fully Paid";
    $badge = "success";
}
?>

<p><strong>Status:</strong>
    <span class="badge bg-<?= $badge ?>">
        <?= $status_label ?>
    </span>
</p>

    </p>

    <hr>

    <?php if ($remaining > 0): ?>
    <h5>Make Payment</h5>
    <form method="POST">
        <input type="number" step="0.01" name="amount" class="form-control" placeholder="Amount (KES)" required>
        <button class="btn btn-primary w-100 mt-3" name="pay">Submit Payment</button>
    </form>
    <?php else: ?>
        <div class="alert alert-info">This debt is fully paid.</div>
    <?php endif; ?>

    <hr>

    <h5>Payment History</h5>

    <table class="table table-bordered table-striped">
        <thead class="table-primary">
        <tr>
            <th>#</th>
            <th>Amount Paid</th>
            <th>Payment Date</th>
            <th>Cashier</th>
        </tr>
        </thead>
        <tbody>
        <?php
        $i = 1;
        while ($row = $payments->fetch_assoc()):
        ?>
            <tr>
                <td><?= $i++ ?></td>
                <td><?= number_format($row['amount_paid'], 2) ?></td>
                <td><?= $row['payment_date'] ?></td>
                <td><?= htmlspecialchars($row['cashier']) ?></td>
            </tr>
        <?php endwhile; ?>
        </tbody>
    </table>

    <a href="admin_customer_debts.php" class="btn btn-success mt-3">← Back to Debts</a>

</div>
<?php include 'footer.php'; ?>
</body>
</html>
