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

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

// Check if user is Buyer
$user_role = $_SESSION['role_name'] ?? '';
if ($user_role !== 'Buyer') {
    header('Location: index.php');
    exit();
}

$user_id = $_SESSION['user_id'];

// Total Purchased Units
$sql_units = "SELECT COUNT(*) as total FROM unit_sales WHERE buyer_id = ?";
$stmt_units = $conn->prepare($sql_units);
$stmt_units->bind_param("i", $user_id);
$stmt_units->execute();
$result_units = $stmt_units->get_result();
$total_units = $result_units->fetch_assoc()['total'] ?? 0;

// Total Investment
$sql_investment = "SELECT SUM(sale_price) as total FROM unit_sales WHERE buyer_id = ?";
$stmt_inv = $conn->prepare($sql_investment);
$stmt_inv->bind_param("i", $user_id);
$stmt_inv->execute();
$result_inv = $stmt_inv->get_result();
$total_investment = $result_inv->fetch_assoc()['total'] ?? 0;

// Total Paid
$sql_paid = "SELECT SUM(CASE WHEN si.status = 'paid' THEN si.amount ELSE 0 END) as total
             FROM sale_installments si
             JOIN unit_sales s ON si.sale_id = s.id
             WHERE s.buyer_id = ?";
$stmt_paid = $conn->prepare($sql_paid);
$stmt_paid->bind_param("i", $user_id);
$stmt_paid->execute();
$result_paid = $stmt_paid->get_result();
$total_paid = $result_paid->fetch_assoc()['total'] ?? 0;

// Pending Installments
$sql_pending = "SELECT COUNT(*) as total, SUM(amount) as total_amount
                FROM sale_installments si
                JOIN unit_sales s ON si.sale_id = s.id
                WHERE s.buyer_id = ? AND si.status = 'pending'";
$stmt_pending = $conn->prepare($sql_pending);
$stmt_pending->bind_param("i", $user_id);
$stmt_pending->execute();
$result_pending = $stmt_pending->get_result();
$pending = $result_pending->fetch_assoc();
$pending_count = $pending['total'] ?? 0;
$pending_amount = $pending['total_amount'] ?? 0;

// Payment Progress
$payment_progress = $total_investment > 0 ? round(($total_paid / $total_investment) * 100, 1) : 0;

// Upcoming Installments
$sql_upcoming = "SELECT si.*, s.id as sale_id, u.unit_number, p.name as property_name
                 FROM sale_installments si
                 JOIN unit_sales s ON si.sale_id = s.id
                 JOIN units u ON s.unit_id = u.id
                 JOIN properties p ON u.property_id = p.id
                 WHERE s.buyer_id = ? AND si.status = 'pending'
                 ORDER BY si.due_date ASC LIMIT 5";
$stmt_upcoming = $conn->prepare($sql_upcoming);
$stmt_upcoming->bind_param("i", $user_id);
$stmt_upcoming->execute();
$result_upcoming = $stmt_upcoming->get_result();

// Recent Payments
$sql_recent = "SELECT p.*, s.id as sale_id, u.unit_number, prop.name as property_name
               FROM payments p
               JOIN sale_installments si ON p.invoice_id = si.id
               JOIN unit_sales s ON si.sale_id = s.id
               JOIN units u ON s.unit_id = u.id
               JOIN properties prop ON u.property_id = prop.id
               WHERE p.payer_id = ?
               ORDER BY p.transaction_date DESC LIMIT 5";
$stmt_recent = $conn->prepare($sql_recent);
$stmt_recent->bind_param("i", $user_id);
$stmt_recent->execute();
$result_recent = $stmt_recent->get_result();
?>
<?php include 'layouts/main.php'; ?>

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

                    <div class="row">
                        <div class="col-xl-3 col-md-6">
                            <div class="card card-animate">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1 overflow-hidden">
                                            <p class="text-uppercase fw-medium text-muted text-truncate mb-0">My Units</p>
                                        </div>
                                        <div class="flex-shrink-0">
                                            <div class="avatar-sm">
                                                <span class="avatar-title bg-soft-primary rounded-circle fs-3">
                                                    <i class="ri-home-4-line text-primary"></i>
                                                </span>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="d-flex align-items-end justify-content-between mt-4">
                                        <div>
                                            <h4 class="fs-22 fw-semibold ff-secondary mb-4">
                                                <?php echo number_format($total_units); ?>
                                            </h4>
                                            <a href="my_purchased_units.php" class="text-decoration-underline">View all</a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-3 col-md-6">
                            <div class="card card-animate">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1 overflow-hidden">
                                            <p class="text-uppercase fw-medium text-muted text-truncate mb-0">Total Investment</p>
                                        </div>
                                        <div class="flex-shrink-0">
                                            <div class="avatar-sm">
                                                <span class="avatar-title bg-soft-info rounded-circle fs-3">
                                                    <i class="ri-money-dollar-circle-line text-info"></i>
                                                </span>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="d-flex align-items-end justify-content-between mt-4">
                                        <div>
                                            <h4 class="fs-22 fw-semibold ff-secondary mb-4">
                                                KES <?php echo number_format($total_investment, 0); ?>
                                            </h4>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-3 col-md-6">
                            <div class="card card-animate">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1 overflow-hidden">
                                            <p class="text-uppercase fw-medium text-muted text-truncate mb-0">Payment Progress</p>
                                        </div>
                                        <div class="flex-shrink-0">
                                            <div class="avatar-sm">
                                                <span class="avatar-title bg-soft-success rounded-circle fs-3">
                                                    <i class="ri-progress-line text-success"></i>
                                                </span>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="d-flex align-items-end justify-content-between mt-4">
                                        <div>
                                            <h4 class="fs-22 fw-semibold ff-secondary mb-4">
                                                <?php echo $payment_progress; ?>%
                                            </h4>
                                            <span class="badge bg-soft-success text-success mb-0">
                                                KES <?php echo number_format($total_paid, 0); ?> paid
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-3 col-md-6">
                            <div class="card card-animate">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1 overflow-hidden">
                                            <p class="text-uppercase fw-medium text-muted text-truncate mb-0">Pending</p>
                                        </div>
                                        <div class="flex-shrink-0">
                                            <div class="avatar-sm">
                                                <span class="avatar-title bg-soft-warning rounded-circle fs-3">
                                                    <i class="ri-time-line text-warning"></i>
                                                </span>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="d-flex align-items-end justify-content-between mt-4">
                                        <div>
                                            <h4 class="fs-22 fw-semibold ff-secondary mb-4">
                                                KES <?php echo number_format($pending_amount, 0); ?>
                                            </h4>
                                            <span class="badge bg-soft-warning text-warning mb-0">
                                                <?php echo $pending_count; ?> installments
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-xl-6">
                            <div class="card">
                                <div class="card-header align-items-center d-flex">
                                    <h4 class="card-title mb-0 flex-grow-1">Upcoming Installments</h4>
                                    <a href="my_installments.php" class="btn btn-soft-primary btn-sm">View All</a>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-nowrap align-middle mb-0">
                                            <thead>
                                                <tr>
                                                    <th>Property/Unit</th>
                                                    <th>Milestone</th>
                                                    <th>Amount</th>
                                                    <th>Due Date</th>
                                                    <th>Action</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if ($result_upcoming && $result_upcoming->num_rows > 0): ?>
                                                    <?php while($installment = $result_upcoming->fetch_assoc()): 
                                                        $days_left = round((strtotime($installment['due_date']) - strtotime('today')) / (60 * 60 * 24));
                                                    ?>
                                                        <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><?php echo htmlspecialchars($installment['milestone_name'] ?? 'Installment'); ?></td>
                                                            <td>
                                                                <span class="fw-semibold">KES <?php echo number_format($installment['amount'], 2); ?></span>
                                                            </td>
                                                            <td>
                                                                <span class="<?php echo $days_left <= 7 ? 'text-danger' : ''; ?>">
                                                                    <?php echo date('M d, Y', strtotime($installment['due_date'])); ?>
                                                                </span>
                                                                <?php if ($days_left <= 7): ?>
                                                                    <br><small class="text-danger"><?php echo $days_left; ?> days left</small>
                                                                <?php endif; ?>
                                                            </td>
                                                            <td>
                                                                <a href="pay_installment.php?installment_id=<?php echo $installment['id']; ?>" 
                                                                   class="btn btn-primary btn-sm">
                                                                    <i class="ri-money-dollar-circle-line me-1"></i>Pay
                                                                </a>
                                                            </td>
                                                        </tr>
                                                    <?php endwhile; ?>
                                                <?php else: ?>
                                                    <tr>
                                                        <td colspan="5" class="text-center py-4">
                                                            <div class="text-muted">No upcoming installments</div>
                                                        </td>
                                                    </tr>
                                                <?php endif; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-6">
                            <div class="card">
                                <div class="card-header align-items-center d-flex">
                                    <h4 class="card-title mb-0 flex-grow-1">Recent Payments</h4>
                                    <a href="my_payment_history.php" class="btn btn-soft-primary btn-sm">View All</a>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-nowrap align-middle mb-0">
                                            <thead>
                                                <tr>
                                                    <th>Date</th>
                                                    <th>Property/Unit</th>
                                                    <th>Amount</th>
                                                    <th>Method</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if ($result_recent && $result_recent->num_rows > 0): ?>
                                                    <?php while($payment = $result_recent->fetch_assoc()): ?>
                                                        <tr>
                                                            <td><?php echo date('M d, Y', strtotime($payment['transaction_date'])); ?></td>
                                                            <td>
                                                                <div>
                                                                    <h5 class="fs-14 mb-0"><?php echo htmlspecialchars($payment['property_name']); ?></h5>
                                                                    <p class="text-muted mb-0 small">Unit: <?php echo htmlspecialchars($payment['unit_number']); ?></p>
                                                                </div>
                                                            </td>
                                                            <td>
                                                                <span class="fw-semibold text-success">KES <?php echo number_format($payment['amount'], 2); ?></span>
                                                            </td>
                                                            <td>
                                                                <span class="badge bg-soft-info"><?php echo htmlspecialchars($payment['payment_method']); ?></span>
                                                            </td>
                                                        </tr>
                                                    <?php endwhile; ?>
                                                <?php else: ?>
                                                    <tr>
                                                        <td colspan="4" class="text-center py-4">
                                                            <div class="text-muted">No payments found</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'; ?>
</body>
</html>
