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

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

// CRM Statistics
$sql_leads_total = "SELECT COUNT(*) as total FROM leads";
$result_leads = $conn->query($sql_leads_total);
$total_leads = $result_leads->fetch_assoc()['total'] ?? 0;

$sql_leads_new = "SELECT COUNT(*) as total FROM leads WHERE status = 'New'";
$result_new = $conn->query($sql_leads_new);
$new_leads = $result_new->fetch_assoc()['total'] ?? 0;

$sql_leads_converted = "SELECT COUNT(*) as total FROM leads WHERE status = 'Converted'";
$result_converted = $conn->query($sql_leads_converted);
$converted_leads = $result_converted->fetch_assoc()['total'] ?? 0;

$sql_sales_total = "SELECT COUNT(*) as total FROM unit_sales WHERE status = 'completed'";
$result_sales = $conn->query($sql_sales_total);
$total_sales = $result_sales->fetch_assoc()['total'] ?? 0;

// Recent leads
$sql_recent_leads = "SELECT l.*, u.first_name as agent_first_name, u.last_name as agent_last_name
                     FROM leads l
                     LEFT JOIN users u ON l.assigned_agent_id = u.id
                     ORDER BY l.created_at DESC LIMIT 10";
$result_recent = $conn->query($sql_recent_leads);
?>
<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'CRM Dashboard')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</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' => 'CRM', 'title' => 'CRM 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">Total Leads</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-user-add-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_leads); ?>
                                            </h4>
                                            <a href="list_leads.php" class="text-decoration-underline">View all leads</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">New Leads</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-inbox-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">
                                                <?php echo number_format($new_leads); ?>
                                            </h4>
                                            <a href="list_leads.php?status=New" class="text-decoration-underline">View new leads</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">Converted</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-checkbox-circle-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 number_format($converted_leads); ?>
                                            </h4>
                                            <a href="list_leads.php?status=Converted" class="text-decoration-underline">View converted</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 Sales</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-handshake-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">
                                                <?php echo number_format($total_sales); ?>
                                            </h4>
                                            <a href="list_sales.php" class="text-decoration-underline">View all sales</a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Recent Leads</h4>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-nowrap align-middle mb-0">
                                            <thead>
                                                <tr>
                                                    <th>Name</th>
                                                    <th>Contact</th>
                                                    <th>Interest</th>
                                                    <th>Budget</th>
                                                    <th>Assigned Agent</th>
                                                    <th>Status</th>
                                                    <th>Created</th>
                                                    <th>Action</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if ($result_recent && $result_recent->num_rows > 0): ?>
                                                    <?php while($lead = $result_recent->fetch_assoc()): ?>
                                                        <tr>
                                                            <td>
                                                                <h5 class="fs-14 mb-0">
                                                                    <?php echo htmlspecialchars($lead['first_name'] . ' ' . $lead['last_name']); ?>
                                                                </h5>
                                                            </td>
                                                            <td>
                                                                <p class="mb-0"><?php echo htmlspecialchars($lead['email'] ?? 'N/A'); ?></p>
                                                                <small class="text-muted"><?php echo htmlspecialchars($lead['phone'] ?? 'N/A'); ?></small>
                                                            </td>
                                                            <td>
                                                                <span class="badge bg-soft-info text-info">
                                                                    <?php echo htmlspecialchars($lead['interest_type'] ?? 'N/A'); ?>
                                                                </span>
                                                            </td>
                                                            <td>
                                                                <?php if ($lead['budget_min'] || $lead['budget_max']): ?>
                                                                    KES <?php echo number_format($lead['budget_min'] ?? 0, 0); ?> - 
                                                                    KES <?php echo number_format($lead['budget_max'] ?? 0, 0); ?>
                                                                <?php else: ?>
                                                                    N/A
                                                                <?php endif; ?>
                                                            </td>
                                                            <td>
                                                                <?php if ($lead['agent_first_name']): ?>
                                                                    <?php echo htmlspecialchars($lead['agent_first_name'] . ' ' . $lead['agent_last_name']); ?>
                                                                <?php else: ?>
                                                                    <span class="text-muted">Unassigned</span>
                                                                <?php endif; ?>
                                                            </td>
                                                            <td>
                                                                <span class="badge bg-soft-primary text-primary">
                                                                    <?php echo htmlspecialchars($lead['status']); ?>
                                                                </span>
                                                            </td>
                                                            <td><?php echo date('M d, Y', strtotime($lead['created_at'])); ?></td>
                                                            <td>
                                                                <a href="lead_details.php?id=<?php echo $lead['id']; ?>" 
                                                                   class="btn btn-soft-secondary btn-sm">
                                                                    <i class="ri-eye-line"></i>
                                                                </a>
                                                            </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 leads 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'; ?>
</body>
</html>
