<?php
session_start();
include 'layouts/dbconn.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$sale_id = $_GET['sale_id'] ?? '';

$sql = "SELECT si.*, s.unit_id, s.buyer_id, s.total_payable, s.status as sale_status,
               u.unit_number, p.name as property_name,
               b.first_name, b.last_name, b.email, b.phone
        FROM sale_installments si
        JOIN unit_sales s ON si.sale_id = s.id
        JOIN units u ON s.unit_id = u.unit_id
        JOIN properties p ON u.property_id = p.id
        JOIN users b ON s.buyer_id = b.id
        WHERE 1=1";

$params = [];
$types = '';

if (!empty($sale_id)) {
    $sql .= " AND si.sale_id = ?";
    $params[] = $sale_id;
    $types .= 'i';
}

$sql .= " ORDER BY si.due_date ASC";

if (!empty($params)) {
    $stmt = $conn->prepare($sql);
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $result = $stmt->get_result();
} else {
    $result = $conn->query($sql);
}

// Get sales for filter
$sql_sales = "SELECT s.*, u.unit_number, p.name as property_name 
              FROM unit_sales s
              JOIN units u ON s.unit_id = u.unit_id
              JOIN properties p ON u.property_id = p.id
              ORDER BY s.created_at DESC";
$result_sales = $conn->query($sql_sales);
?>
<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Sales Installments')); ?>
    <?php include 'layouts/head-css.php'; ?>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>

        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'Sales Management', 'title' => 'Sales Installments')); ?>

                    <div class="row mb-3">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-body">
                                    <form method="GET" class="row g-3">
                                        <div class="col-md-4">
                                            <label class="form-label">Filter by Sale</label>
                                            <select class="form-select" name="sale_id" onchange="this.form.submit()">
                                                <option value="">All Sales</option>
                                                <?php while($sale = $result_sales->fetch_assoc()): ?>
                                                    <option value="<?php echo $sale['id']; ?>" 
                                                            <?php echo $sale_id == $sale['id'] ? 'selected' : ''; ?>>
                                                        <?php echo htmlspecialchars($sale['property_name'] . ' - Unit ' . $sale['unit_number']); ?>
                                                    </option>
                                                <?php endwhile; ?>
                                            </select>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header align-items-center d-flex">
                                    <h4 class="card-title mb-0 flex-grow-1">Installment Schedule</h4>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-nowrap align-middle mb-0">
                                            <thead>
                                                <tr>
                                                    <th>Sale</th>
                                                    <th>Buyer</th>
                                                    <th>Milestone</th>
                                                    <th>Amount</th>
                                                    <th>Due Date</th>
                                                    <th>Status</th>
                                                    <th>Paid Date</th>
                                                    <th>Action</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if ($result && $result->num_rows > 0): ?>
                                                    <?php while($installment = $result->fetch_assoc()): ?>
                                                        <?php
                                                        $due_date = strtotime($installment['due_date']);
                                                        $today = strtotime('today');
                                                        $is_overdue = $due_date < $today && $installment['status'] == 'pending';
                                                        ?>
                                                        <tr>
                                                            <td>
                                                                <div>
                                                                    <h5 class="fs-14 mb-0"><?php echo htmlspecialchars($installment['property_name']); ?></h5>
                                                                    <p class="text-muted mb-0 small">Unit: <?php echo htmlspecialchars($installment['unit_number']); ?></p>
                                                                </div>
                                                            </td>
                                                            <td>
                                                                <div>
                                                                    <h5 class="fs-14 mb-0">
                                                                        <?php echo htmlspecialchars($installment['first_name'] . ' ' . $installment['last_name']); ?>
                                                                    </h5>
                                                                    <p class="text-muted mb-0 small"><?php echo htmlspecialchars($installment['email']); ?></p>
                                                                </div>
                                                            </td>
                                                            <td>
                                                                <span class="fw-semibold"><?php echo htmlspecialchars($installment['milestone_name'] ?? 'Installment'); ?></span>
                                                            </td>
                                                            <td>
                                                                <span class="fw-semibold">KES <?php echo number_format($installment['amount'], 2); ?></span>
                                                            </td>
                                                            <td>
                                                                <?php if ($is_overdue): ?>
                                                                    <span class="text-danger"><?php echo date('M d, Y', $due_date); ?></span>
                                                                    <small class="d-block text-danger">Overdue</small>
                                                                <?php else: ?>
                                                                    <?php echo date('M d, Y', $due_date); ?>
                                                                <?php endif; ?>
                                                            </td>
                                                            <td>
                                                                <?php
                                                                $status_colors = [
                                                                    'paid' => 'success',
                                                                    'pending' => 'warning',
                                                                    'overdue' => 'danger'
                                                                ];
                                                                $color = $status_colors[$installment['status']] ?? 'secondary';
                                                                ?>
                                                                <span class="badge bg-soft-<?php echo $color; ?> text-<?php echo $color; ?>">
                                                                    <?php echo ucfirst($installment['status']); ?>
                                                                </span>
                                                            </td>
                                                            <td>
                                                                <?php echo $installment['paid_date'] ? date('M d, Y', strtotime($installment['paid_date'])) : 'N/A'; ?>
                                                            </td>
                                                            <td>
                                                                <?php if ($installment['status'] == 'pending'): ?>
                                                                    <button class="btn btn-soft-primary btn-sm" 
                                                                            onclick="recordPayment(<?php echo $installment['id']; ?>)">
                                                                        <i class="ri-money-dollar-circle-line"></i> Record Payment
                                                                    </button>
                                                                <?php else: ?>
                                                                    <span class="text-muted">-</span>
                                                                <?php endif; ?>
                                                            </td>
                                                        </tr>
                                                    <?php endwhile; ?>
                                                <?php else: ?>
                                                    <tr>
                                                        <td colspan="8" class="text-center py-4">
                                                            <div class="text-muted">
                                                                <i class="ri-inbox-line fs-48"></i>
                                                                <p class="mt-2">No installments found</p>
                                                            </div>
                                                        </td>
                                                    </tr>
                                                <?php endif; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script>
        function recordPayment(installmentId) {
            window.location.href = 'record_installment_payment.php?installment_id=' + installmentId;
        }
    </script>
</body>
</html>
