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

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

$user_id = $_SESSION['user_id'];

$sql = "SELECT s.*, u.unit_number, u.floor_level, u.bedrooms, u.bathrooms,
               p.name as property_name, p.location_area
        FROM unit_sales s
        JOIN units u ON s.unit_id = u.id
        JOIN properties p ON u.property_id = p.id
        WHERE s.buyer_id = ?
        ORDER BY s.created_at DESC";

$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();
?>
<?php include 'layouts/main.php'; ?>

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

                    <div class="row">
                        <?php if ($result && $result->num_rows > 0): ?>
                            <?php while($sale = $result->fetch_assoc()): 
                                // Calculate payment progress
                                $sql_progress = "SELECT 
                                                    SUM(CASE WHEN status = 'paid' THEN amount ELSE 0 END) as paid,
                                                    SUM(amount) as total
                                                FROM sale_installments 
                                                WHERE sale_id = ?";
                                $stmt_prog = $conn->prepare($sql_progress);
                                $stmt_prog->bind_param("i", $sale['id']);
                                $stmt_prog->execute();
                                $result_prog = $stmt_prog->get_result();
                                $progress = $result_prog->fetch_assoc();
                                $paid = $progress['paid'] ?? 0;
                                $total = $progress['total'] ?? $sale['total_payable'];
                                $progress_percent = $total > 0 ? ($paid / $total) * 100 : 0;
                            ?>
                                <div class="col-xl-6 col-md-12">
                                    <div class="card">
                                        <div class="card-body">
                                            <h5 class="card-title"><?php echo htmlspecialchars($sale['property_name']); ?></h5>
                                            <p class="text-muted mb-2">
                                                <i class="ri-home-4-line me-1"></i>
                                                Unit <?php echo htmlspecialchars($sale['unit_number']); ?>
                                                (<?php echo $sale['bedrooms']; ?>BR, <?php echo $sale['bathrooms']; ?>BA)
                                            </p>
                                            <p class="text-muted mb-3">
                                                <i class="ri-map-pin-line me-1"></i>
                                                <?php echo htmlspecialchars($sale['location_area']); ?>
                                            </p>
                                            
                                            <div class="mb-3">
                                                <div class="d-flex justify-content-between mb-1">
                                                    <span>Payment Progress</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>
                                                <small class="text-muted">
                                                    KES <?php echo number_format($paid, 2); ?> / KES <?php echo number_format($total, 2); ?>
                                                </small>
                                            </div>
                                            
                                            <div class="d-flex gap-2">
                                                <a href="my_installments.php?sale_id=<?php echo $sale['id']; ?>" 
                                                   class="btn btn-primary btn-sm flex-fill">
                                                    <i class="ri-calendar-line me-1"></i>View Installments
                                                </a>
                                                <a href="my_documents.php?sale_id=<?php echo $sale['id']; ?>" 
                                                   class="btn btn-info btn-sm flex-fill">
                                                    <i class="ri-file-line me-1"></i>Documents
                                                </a>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            <?php endwhile; ?>
                        <?php else: ?>
                            <div class="col-12">
                                <div class="card">
                                    <div class="card-body text-center py-5">
                                        <i class="ri-house-line fs-48 text-muted mb-3"></i>
                                        <h5>No Purchased Units</h5>
                                        <p class="text-muted">You haven't purchased any units yet.</p>
                                    </div>
                                </div>
                            </div>
                        <?php endif; ?>
                    </div>

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

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