<?php 
// ১. টাইমজোন এবং প্রফেশনাল পারশিয়াল ফাইল ইনক্লুড করা
date_default_timezone_set('Asia/Dhaka'); 
include 'includes/header.php'; 
include 'includes/sidebar.php'; 
require_once '../db_connect.php'; 

// ২. পেজিনেশন সেটিংস
$limit = 50; 
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
if ($page < 1) $page = 1;
$offset = ($page - 1) * $limit;

$msg = "";

// ৩. ডিলিট লজিক
if (isset($_GET['delete_id'])) {
    $id = $_GET['delete_id'];
    try {
        $stmt = $pdo->prepare("DELETE FROM online_admissions WHERE id = ?");
        if($stmt->execute([$id])){
            echo "<script>window.location.href='fb_leads?msg=deleted';</script>";
            exit;
        }
    } catch (PDOException $e) {}
}

// ৪. স্ট্যাটাস আপডেট লজিক
if (isset($_POST['update_status'])) {
    $id = $_POST['lead_id'];
    $new_status = $_POST['status'];
    try {
        $stmt = $pdo->prepare("UPDATE online_admissions SET status = ? WHERE id = ?");
        if($stmt->execute([$new_status, $id])){
            $msg = "<div class='alert alert-success border-0 border-start border-success border-4 shadow-sm mb-4'>
                        <i class='fas fa-check-circle me-2'></i> স্ট্যাটাস সফলভাবে আপডেট হয়েছে!
                    </div>";
        }
    } catch (PDOException $e) {}
}

// ৫. ডাটাবেস থেকে তথ্য নিয়ে আসা
$total_rows = $pdo->query("SELECT COUNT(*) FROM online_admissions")->fetchColumn();
$total_pages = ceil($total_rows / $limit);

$stmt = $pdo->prepare("SELECT * FROM online_admissions ORDER BY id DESC LIMIT $offset, $limit");
$stmt->execute();
$leads = $stmt->fetchAll();

// অ্যানালিটিক্স ডাটা
try {
    $view_stats = $pdo->query("SELECT page_name, views FROM page_analytics")->fetchAll(PDO::FETCH_KEY_PAIR);
    $v_admission = $view_stats['online_admission'] ?? 0;
    $v_branch = $view_stats['branch_recruitment'] ?? 0;
} catch (PDOException $e) { $v_admission = $v_branch = 0; }

$sn = $offset + 1;
?>

<style>
    /* --- Modern Management UI Custom CSS --- */
    :root { --admin-green: #0a5f3e; --admin-yellow: #ffb800; }
    .main-content { background-color: #f8fafc; min-height: 100vh; padding: 20px; }
    
    .dashboard-header {
        background: #fff; padding: 20px 30px; border-radius: 15px;
        box-shadow: 0 5px 20px rgba(0,0,0,0.03); margin-bottom: 35px;
    }
    
    .custom-card {
        background: #fff; border: none; border-radius: 18px;
        box-shadow: 0 10px 40px rgba(0,0,0,0.05); overflow: hidden;
    }

    .stat-box {
        background: #fff; padding: 20px; border-radius: 15px;
        border-bottom: 4px solid var(--admin-green); transition: 0.3s;
    }
    .stat-box:hover { transform: translateY(-5px); box-shadow: 0 10px 20px rgba(0,0,0,0.05); }

    .filter-btn {
        background: #fff; border: 1px solid #eee; padding: 8px 18px;
        border-radius: 50px; font-weight: 700; color: #64748b;
        cursor: pointer; transition: 0.3s; font-size: 13px; margin-right: 5px;
    }
    .filter-btn.active { background: var(--admin-green); color: #fff; border-color: var(--admin-green); }

    .table thead { background-color: #f8fafc; }
    .table thead th {
        border: none; padding: 18px 20px; color: #64748b;
        font-weight: 700; text-transform: uppercase; font-size: 12px;
    }
    .table tbody td { padding: 15px 20px; border-bottom: 1px solid #f1f5f9; vertical-align: middle; }
    
    .status-select {
        border-radius: 50px; padding: 5px 12px; font-size: 12px; font-weight: 700; border: none; cursor: pointer;
    }
    .st-Pending { background: #fef3c7; color: #92400e; }
    .st-Called { background: #e0f2fe; color: #0369a1; }
    .st-Admitted { background: #ecfdf5; color: #059669; }

    .btn-action {
        width: 35px; height: 35px; display: inline-flex; align-items: center;
        justify-content: center; border-radius: 10px; transition: 0.3s; border: none;
    }
    .btn-delete { background: #fee2e2; color: #dc2626; }
    .btn-delete:hover { background: #dc2626; color: #fff; }

    .branch-row { background-color: #fffdf5 !important; border-left: 5px solid var(--admin-yellow) !important; }

    .fade-up { animation: fadeInUp 0.6s ease-out forwards; }
    @keyframes fadeInUp { 0% { opacity: 0; transform: translateY(20px); } 100% { opacity: 1; transform: translateY(0); } }

    @media (max-width: 768px) {
        .dashboard-header { flex-direction: column; gap: 15px; text-align: center; }
        .table thead { display: none; }
        .table tr { display: block; border: 1px solid #eee; margin-bottom: 15px; border-radius: 15px; padding: 10px; background: #fff; }
        .table td { display: flex; justify-content: space-between; border: none; padding: 8px 10px; font-size: 14px; text-align: right; }
        .table td::before { content: attr(data-label); font-weight: 800; color: #64748b; text-align: left; }
    }
</style>

<div class="main-content">
    
    <div class="dashboard-header d-flex justify-content-between align-items-center fade-up">
        <div class="d-flex align-items-center">
            <button class="btn btn-light d-md-none me-3" id="sidebarToggle">
                <i class="fas fa-bars text-success"></i>
            </button>
            <h4 class="mb-0 fw-bold" style="color: var(--admin-green);">
                <i class=""></i> ফেসবুক লিড ম্যানেজমেন্ট
            </h4>
        </div>
        <div class="d-flex gap-2">
            <a href="../online-admission" target="_blank" class="btn btn-outline-success btn-sm rounded-pill px-3 fw-bold shadow-sm">ভর্তি পেজ</a>
            <a href="../branch-recruitment" target="_blank" class="btn btn-outline-warning btn-sm rounded-pill px-3 fw-bold shadow-sm">শাখা পেজ</a>
        </div>
    </div>

    <div class="row g-4 mb-5 fade-up" style="animation-delay: 0.1s;">
        <div class="col-6 col-md-3">
            <div class="stat-box shadow-sm">
                <div class="text-muted small fw-bold">ভর্তি পেজ ভিউ</div>
                <div class="h4 fw-bold mb-0 text-dark"><?= number_format($v_admission) ?></div>
            </div>
        </div>
        <div class="col-6 col-md-3">
            <div class="stat-box shadow-sm" style="border-color: var(--admin-yellow);">
                <div class="text-muted small fw-bold">শাখা পেজ ভিউ</div>
                <div class="h4 fw-bold mb-0 text-dark"><?= number_format($v_branch) ?></div>
            </div>
        </div>
        <div class="col-6 col-md-3">
            <div class="stat-box shadow-sm">
                <div class="text-muted small fw-bold">মোট লিড</div>
                <div class="h4 fw-bold mb-0 text-dark"><?= number_format($total_rows) ?></div>
            </div>
        </div>
        <div class="col-6 col-md-3">
            <div class="stat-box shadow-sm">
                <div class="text-muted small fw-bold">পেজ নম্বর</div>
                <div class="h4 fw-bold mb-0 text-dark"><?= $page ?> / <?= $total_pages ?></div>
            </div>
        </div>
    </div>

    <?= $msg; ?>
    <?php if(isset($_GET['msg']) && $_GET['msg'] == 'deleted'): ?>
        <div class="alert alert-success border-0 border-start border-success border-4 shadow-sm fade-up mb-4">
            <i class="fas fa-check-circle me-2"></i> লিডটি সফলভাবে ডিলিট করা হয়েছে!
        </div>
    <?php endif; ?>

    <div class="d-md-flex justify-content-between align-items-center mb-4 px-2 fade-up">
        <div class="filter-tabs mb-3 mb-md-0 d-flex overflow-auto">
            <button class="filter-btn active" onclick="filterType('all')">সব লিড</button>
            <button class="filter-btn" onclick="filterType('course')">ভর্তি আবেদন</button>
            <button class="filter-btn" onclick="filterType('branch')">শাখা নিয়োগ</button>
        </div>
        <div class="search-box">
            <input type="text" id="leadSearch" class="form-control rounded-pill border-0 shadow-sm px-4" style="width: 280px; background: #fff;" placeholder="নাম বা মোবাইল দিয়ে খুঁজুন...">
        </div>
    </div>

    <div class="custom-card fade-up" style="animation-delay: 0.2s;">
        <div class="table-responsive">
            <table class="table table-hover mb-0 align-middle">
                <thead>
                    <tr>
                        <th class="ps-4">Sl.</th>
                        <th>আবেদনকারী</th>
                        <th>মোবাইল নম্বর</th>
                        <th>কোর্স / ধরণ</th>
                        <th>তারিখ ও সময় (BD)</th>
                        <th>স্ট্যাটাস</th>
                        <th class="text-center pe-4">অ্যাকশন</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if(!empty($leads)): foreach($leads as $lead): 
                        $isBranch = (strpos(strtolower($lead['course']), 'branch') !== false);
                    ?>
                    <tr class="lead-item <?= $isBranch ? 'branch-row type-branch' : 'type-course' ?>">
                        <td class="ps-4 text-muted fw-bold"><?= str_pad($sn++, 2, "0", STR_PAD_LEFT); ?>.</td>
                        <td data-label="আবেদনকারী">
                            <div class="fw-bold text-dark name-text"><?= htmlspecialchars($lead['name']); ?></div>
                            <small class="text-muted"><i class="fas fa-map-marker-alt me-1"></i> <?= htmlspecialchars($lead['address']); ?></small>
                        </td>
                        <td data-label="মোবাইল">
                            <a href="tel:<?= $lead['phone'] ?>" class="text-success fw-bold text-decoration-none phone-text">
                                <i class="fas fa-phone-alt me-1"></i> <?= htmlspecialchars($lead['phone']); ?>
                            </a>
                        </td>
                        <td data-label="কোর্স">
                            <?php if($isBranch): ?>
                                <span class="badge bg-warning text-dark rounded-pill px-3 py-2 fw-bold" style="font-size: 11px;">BRANCH APPLICATION</span>
                            <?php else: ?>
                                <span class="badge bg-light border text-dark rounded-pill px-3 py-2 fw-bold" style="font-size: 11px;"><?= $lead['course']; ?></span>
                            <?php endif; ?>
                        </td>
                        <td data-label="তারিখ">
                            <div class="small fw-bold text-dark"><?= date('d M Y', strtotime($lead['created_at'])); ?></div>
                            <div class="text-muted small" style="font-size: 10px;"><?= date('h:i A', strtotime($lead['created_at'])); ?></div>
                        </td>
                        <td data-label="স্ট্যাটাস">
                            <form method="POST">
                                <input type="hidden" name="lead_id" value="<?= $lead['id']; ?>"><input type="hidden" name="update_status" value="1">
                                <select name="status" class="status-select st-<?= $lead['status']; ?>" onchange="this.form.submit()">
                                    <option value="Pending" <?= $lead['status'] == 'Pending' ? 'selected' : ''; ?>>Pending</option>
                                    <option value="Called" <?= $lead['status'] == 'Called' ? 'selected' : ''; ?>>Called</option>
                                    <option value="Admitted" <?= $lead['status'] == 'Admitted' ? 'selected' : ''; ?>>Admitted</option>
                                </select>
                            </form>
                        </td>
                        <td class="text-center pe-4">
                            <div class="d-flex justify-content-center">
                                <a href="edit_fb_lead?id=<?= $lead['id']; ?>" class="btn-action bg-primary bg-opacity-10 text-primary me-2" title="এডিট">
                                    <i class="fas fa-edit"></i>
                                </a>
                                <a href="?delete_id=<?= $lead['id']; ?>" class="btn-action btn-delete" onclick="return confirm('আপনি কি নিশ্চিত?')" title="ডিলিট">
                                    <i class="fas fa-trash-alt"></i>
                                </a>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; else: ?>
                    <tr><td colspan="7" class="text-center py-5 text-muted">কোনো ডাটা পাওয়া যায়নি।</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

    <?php if($total_pages > 1): ?>
    <div class="d-flex flex-column flex-md-row justify-content-between align-items-center mt-4 px-2 fade-up">
        <div class="text-muted small fw-bold mb-3 mb-md-0">মোট লিড: <?= $total_rows ?> টি</div>
        <nav>
            <ul class="pagination mb-0">
                <li class="page-item <?= ($page <= 1) ? 'disabled' : '' ?>">
                    <a class="page-link" href="?page=<?= $page - 1 ?>"><i class="fas fa-chevron-left"></i></a>
                </li>
                <?php 
                $start = max(1, $page - 2);
                $end = min($total_pages, $page + 2);
                for($i = $start; $i <= $end; $i++): 
                ?>
                    <li class="page-item <?= ($page == $i) ? 'active' : '' ?>">
                        <a class="page-link" href="?page=<?= $i ?>"><?= $i ?></a>
                    </li>
                <?php endfor; ?>
                <li class="page-item <?= ($page >= $total_pages) ? 'disabled' : '' ?>">
                    <a class="page-link" href="?page=<?= $page + 1 ?>"><i class="fas fa-chevron-right"></i></a>
                </li>
            </ul>
        </nav>
    </div>
    <?php endif; ?>
</div>

<script>
    function filterType(type) {
        document.querySelectorAll('.filter-btn').forEach(btn => btn.classList.remove('active'));
        event.target.classList.add('active');

        document.querySelectorAll('.lead-item').forEach(row => {
            if(type === 'all') row.style.display = "";
            else if(type === 'branch') row.style.display = row.classList.contains('branch-row') ? "" : "none";
            else if(type === 'course') row.style.display = row.classList.contains('type-course') ? "" : "none";
        });
    }

    document.getElementById('leadSearch').addEventListener('keyup', function() {
        let filter = this.value.toLowerCase();
        document.querySelectorAll('.lead-item').forEach(row => {
            let text = row.innerText.toLowerCase();
            row.style.display = text.includes(filter) ? "" : "none";
        });
    });

    document.getElementById('sidebarToggle').addEventListener('click', function(e) {
        e.stopPropagation();
        (document.getElementById('sidebarMenu') || document.querySelector('.sidebar')).classList.toggle('active');
    });
</script>

<?php include 'includes/footer.php'; ?>