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

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

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

if (empty($sale_id)) {
    header('Location: list_sales.php');
    exit();
}

// Get sale details
$sql = "SELECT s.*, u.unit_number, u.bedrooms, u.bathrooms,
               p.name as property_name, p.location_area,
               u2.first_name as buyer_first, u2.last_name as buyer_last, u2.email as buyer_email
        FROM unit_sales s
        JOIN units u ON s.unit_id = u.id
        JOIN properties p ON u.property_id = p.id
        LEFT JOIN users u2 ON s.buyer_id = u2.id
        WHERE s.id = ?";

$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $sale_id);
$stmt->execute();
$result = $stmt->get_result();
$sale = $result->fetch_assoc();

if (!$sale) {
    header('Location: list_sales.php');
    exit();
}

// Get installments
$sql_installments = "SELECT * FROM sale_installments 
                     WHERE sale_id = ? 
                     ORDER BY due_date ASC";

$stmt_installments = $conn->prepare($sql_installments);
$stmt_installments->bind_param("i", $sale_id);
$stmt_installments->execute();
$result_installments = $stmt_installments->get_result();

// Calculate payment progress
$total_paid = 0;
$total_due = 0;
while($inst = $result_installments->fetch_assoc()) {
    if ($inst['status'] == 'paid') {
        $total_paid += $inst['amount'];
    }
    $total_due += $inst['amount'];
}
$result_installments->data_seek(0);
$progress_percent = $total_due > 0 ? ($total_paid / $total_due) * 100 : 0;
?>
<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Sale Details')); ?>
    <?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', 'title' => 'Sale Details')); ?>

                    <div class="row mb-3">
                        <div class="col-12">
                            <a href="list_sales.php" class="btn btn-light">
                                <i class="ri-arrow-left-line me-1"></i>Back to Sales
                            </a>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-xl-8">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Sale Agreement</h4>
                                </div>
                                <div class="card-body">
                                    <div class="row mb-3">
                                        <div class="col-md-6">
                                            <p class="mb-2"><strong>Property:</strong> <?php echo htmlspecialchars($sale['property_name']); ?></p>
                                            <p class="mb-2"><strong>Unit:</strong> <?php echo htmlspecialchars($sale['unit_number']); ?></p>
                                            <p class="mb-2"><strong>Location:</strong> <?php echo htmlspecialchars($sale['location_area']); ?></p>
                                            <p class="mb-2"><strong>Buyer:</strong> 
                                                <?php echo htmlspecialchars($sale['buyer_first'] . ' ' . $sale['buyer_last']); ?>
                                                <br><small class="text-muted"><?php echo htmlspecialchars($sale['buyer_email']); ?></small>
                                            </p>
                                        </div>
                                        <div class="col-md-6">
                                            <p class="mb-2"><strong>Sale Price:</strong> KES <?php echo number_format($sale['sale_price'], 2); ?></p>
                                            <p class="mb-2"><strong>Total Payable:</strong> KES <?php echo number_format($sale['total_payable'], 2); ?></p>
                                            <p class="mb-2"><strong>Status:</strong> 
                                                <span class="badge bg-soft-<?php echo strtolower($sale['status']) == 'completed' ? 'success' : 'warning'; ?>">
                                                    <?php echo htmlspecialchars($sale['status']); ?>
                                                </span>
                                            </p>
                                            <p class="mb-2"><strong>Agreement Date:</strong> <?php echo date('M d, Y', strtotime($sale['agreement_date'])); ?></p>
                                        </div>
                                    </div>

                                    <div class="mb-3">
                                        <h6 class="text-muted mb-2">Payment Progress</h6>
                                        <div class="d-flex justify-content-between mb-1">
                                            <span>KES <?php echo number_format($total_paid, 2); ?> / KES <?php echo number_format($total_due, 2); ?></span>
                                            <span class="fw-semibold"><?php echo number_format($progress_percent, 1); ?>%</span>
                                        </div>
                                        <div class="progress">
                                            <div class="progress-bar bg-success" role="progressbar" 
                                                 style="width: <?php echo $progress_percent; ?>%">
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="card mt-3">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Installment Schedule</h4>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-nowrap align-middle mb-0">
                                            <thead>
                                                <tr>
                                                    <th>Milestone</th>
                                                    <th>Amount</th>
                                                    <th>Due Date</th>
                                                    <th>Status</th>
                                                    <th>Paid Date</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if ($result_installments && $result_installments->num_rows > 0): ?>
                                                    <?php while($installment = $result_installments->fetch_assoc()): ?>
                                                        <tr>
                                                            <td><?php echo htmlspecialchars($installment['milestone_name'] ?? 'Installment'); ?></td>
                                                            <td>KES <?php echo number_format($installment['amount'], 2); ?></td>
                                                            <td><?php echo date('M d, Y', strtotime($installment['due_date'])); ?></td>
                                                            <td>
                                                                <span class="badge bg-soft-<?php echo $installment['status'] == 'paid' ? 'success' : 'warning'; ?>">
                                                                    <?php echo ucfirst($installment['status']); ?>
                                                                </span>
                                                            </td>
                                                            <td>
                                                                <?php echo $installment['paid_date'] ? date('M d, Y', strtotime($installment['paid_date'])) : 'N/A'; ?>
                                                            </td>
                                                        </tr>
                                                    <?php endwhile; ?>
                                                <?php else: ?>
                                                    <tr>
                                                        <td colspan="5" class="text-center py-4">
                                                            <div class="text-muted">No installments found</div>
                                                        </td>
                                                    </tr>
                                                <?php endif; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-4">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Quick Actions</h4>
                                </div>
                                <div class="card-body">
                                    <a href="sales_installments.php?sale_id=<?php echo $sale_id; ?>" class="btn btn-primary w-100 mb-2">
                                        <i class="ri-calendar-line me-1"></i>Manage Installments
                                    </a>
                                    <a href="unit_details.php?id=<?php echo $sale['unit_id']; ?>" class="btn btn-secondary w-100">
                                        <i class="ri-home-4-line me-1"></i>View Unit
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>

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

    <?php include 'layouts/vendor-scripts.php'; ?>
</body>
</html>
