<?php
// admin-dashboard.php
ini_set('display_errors', 0);
error_reporting(E_ALL);
ini_set('log_errors', 1);
ini_set('error_log', 'php_errors.log');

session_start();
require_once '../config/config.php';

// === SECURITY: Must be admin ===
if (!isset($_SESSION['user_id']) || ($_SESSION['role'] ?? '') !== 'admin') {
    header('Location: ../login.php');
    exit;
}

// === IMPERSONATION DETECTION ===
$impersonating = false;
$impersonated_id = null;
if (isset($_GET['id'])) {
    $imp_id = (int)$_GET['id'];
    $stmt = $conn->prepare("SELECT id FROM companies WHERE id = ?");
    $stmt->bind_param('i', $imp_id);
    $stmt->execute();
    if ($stmt->get_result()->num_rows === 1) {
        $impersonating = true;
        $impersonated_id = $imp_id;
    }
    $stmt->close();
}

// === FETCH GLOBAL STATS ===
$companies = [];
$sql = "SELECT c.id, c.company_name, c.company_email,
               COUNT(l.id) AS total_leads,
               SUM(CASE WHEN l.converted = 1 THEN 1 ELSE 0 END) AS converted_leads
        FROM companies c
        LEFT JOIN leads l ON c.id = l.company_id
        GROUP BY c.id
        ORDER BY c.company_name";

$stmt = $conn->prepare($sql);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    $companies[] = $row;
}
$stmt->close();

// Global totals
$totalCompanies   = count($companies);
$totalLeads       = array_sum(array_column($companies, 'total_leads'));
$convertedLeads   = array_sum(array_column($companies, 'converted_leads'));
$pendingLeads     = $totalLeads - $convertedLeads;
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Dashboard - Lead Management System</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
    :root {
        --primary: #7c3aed;
        --primary-light: #8b5cf6;
        --primary-dark: #6d28d9;
        --secondary: #06b6d4;
        --success: #10b981;
        --warning: #f59e0b;
        --danger: #ef4444;
        --dark: #0f172a;
        --darker: #020617;
        --light: #f8fafc;
        --card-bg: rgba(255, 255, 255, 0.08);
        --card-bg-hover: rgba(255, 255, 255, 0.12);
        --border: rgba(255, 255, 255, 0.1);
        --text: #f1f5f9;
        --text-light: #cbd5e1;
        --text-lighter: #94a3b8;
        --shadow: 0 20px 40px rgba(0, 0, 0, .3);
        --shadow-lg: 0 25px 50px rgba(0, 0, 0, .4);
        --radius: 1rem;
        --radius-sm: .75rem;
        --transition: all .3s cubic-bezier(.4, 0, .2, 1);
    }

    * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
    }

    body {
        font-family: 'Inter', sans-serif;
        background: linear-gradient(135deg, var(--darker), var(--dark));
        color: var(--text);
        min-height: 100vh;
        line-height: 1.6;
    }

    .background {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        z-index: -1;
        overflow: hidden;
    }

    .gradient-orb {
        position: absolute;
        border-radius: 50%;
        filter: blur(80px);
        opacity: .3;
        animation: float-orb 25s ease-in-out infinite;
    }

    .orb-1 {
        width: 500px;
        height: 500px;
        background: linear-gradient(45deg, var(--primary), var(--secondary));
        top: -200px;
        left: -200px;
    }

    .orb-2 {
        width: 400px;
        height: 400px;
        background: linear-gradient(45deg, var(--secondary), var(--success));
        bottom: -150px;
        right: -150px;
        animation-delay: -8s;
    }

    @keyframes float-orb {

        0%,
        100% {
            transform: translate(0, 0) scale(1);
        }

        25% {
            transform: translate(100px, 100px) scale(1.1);
        }

        50% {
            transform: translate(0, 200px) scale(.9);
        }

        75% {
            transform: translate(-100px, 100px) scale(1.05);
        }
    }

    .container {
        max-width: 1400px;
        margin: 0 auto;
        padding: 2rem;
    }

    .header {
        text-align: center;
        margin-bottom: 3rem;
        position: relative;
    }

    .header::after {
        content: '';
        position: absolute;
        bottom: -1rem;
        left: 50%;
        transform: translateX(-50%);
        width: 100px;
        height: 3px;
        background: linear-gradient(90deg, var(--primary), var(--secondary));
        border-radius: 2px;
    }

    .header h1 {
        font-size: 3rem;
        font-weight: 700;
        background: linear-gradient(135deg, var(--text), var(--primary-light));
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        margin-bottom: .5rem;
    }

    .header p {
        color: var(--text-light);
        font-size: 1.1rem;
    }

    .stats-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
        gap: 1.5rem;
        margin-bottom: 3rem;
    }

    .stat-card {
        background: var(--card-bg);
        backdrop-filter: blur(20px);
        border: 1px solid var(--border);
        border-radius: var(--radius);
        padding: 2rem;
        text-align: center;
        transition: var(--transition);
        position: relative;
        overflow: hidden;
    }

    .stat-card::before {
        content: '';
        position: absolute;
        top: 0;
        left: -100%;
        width: 100%;
        height: 100%;
        background: linear-gradient(90deg, transparent, rgba(255, 255, 255, .1), transparent);
        transition: left .6s;
    }

    .stat-card:hover::before {
        left: 100%;
    }

    .stat-card:hover {
        transform: translateY(-8px);
        border-color: var(--primary-light);
        box-shadow: var(--shadow);
    }

    .stat-icon {
        width: 70px;
        height: 70px;
        margin: 0 auto 1rem;
        background: linear-gradient(135deg, var(--primary), var(--primary-light));
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 1.8rem;
        color: white;
    }

    .stat-value {
        font-size: 2.5rem;
        font-weight: 700;
        margin-bottom: .5rem;
        background: linear-gradient(135deg, var(--text), var(--primary-light));
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
    }

    .stat-label {
        color: var(--text-light);
        font-size: 1rem;
        font-weight: 500;
    }

    .companies-section {
        margin-bottom: 3rem;
    }

    .section-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 2rem;
        flex-wrap: wrap;
        gap: 1rem;
    }

    .section-title {
        font-size: 1.8rem;
        font-weight: 600;
        color: var(--text);
        display: flex;
        align-items: center;
        gap: .75rem;
    }

    .section-title i {
        color: var(--primary-light);
    }

    .search-box {
        position: relative;
        max-width: 300px;
        flex: 1;
        min-width: 250px;
    }

    .search-input {
        width: 100%;
        padding: .875rem 1rem .875rem 3rem;
        background: var(--card-bg);
        border: 1px solid var(--border);
        border-radius: var(--radius-sm);
        color: var(--text);
        font-size: .95rem;
        transition: var(--transition);
    }

    .search-input:focus {
        outline: none;
        border-color: var(--primary-light);
        box-shadow: 0 0 0 3px rgba(124, 58, 237, .2);
    }

    .search-icon {
        position: absolute;
        left: 1rem;
        top: 50%;
        transform: translateY(-50%);
        color: var(--text-lighter);
    }

    .search-hint {
        font-size: .75rem;
        color: var(--text-lighter);
        margin-top: .25rem;
        padding-left: 3rem;
    }

    .refresh-btn {
        background: var(--card-bg);
        border: 1px solid var(--border);
        color: var(--text-light);
        padding: .75rem 1rem;
        border-radius: var(--radius-sm);
        cursor: pointer;
        display: flex;
        align-items: center;
        gap: .5rem;
        font-size: .9rem;
        transition: var(--transition);
    }

    .refresh-btn:hover {
        background: var(--card-bg-hover);
        border-color: var(--primary-light);
        color: var(--text);
    }

    .companies-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
        gap: 1.5rem;
    }

    .company-card {
        background: var(--card-bg);
        backdrop-filter: blur(20px);
        border: 1px solid var(--border);
        border-radius: var(--radius);
        padding: 2rem;
        transition: var(--transition);
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }

    .company-card::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        width: 4px;
        height: 100%;
        background: linear-gradient(180deg, var(--primary), var(--secondary));
        transform: scaleY(0);
        transition: transform .3s ease;
    }

    .company-card:hover::before {
        transform: scaleY(1);
    }

    .company-card:hover {
        transform: translateY(-5px);
        background: var(--card-bg-hover);
        border-color: var(--primary-light);
        box-shadow: var(--shadow);
    }

    .company-header {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        margin-bottom: 1rem;
    }

    .company-name {
        font-size: 1.3rem;
        font-weight: 600;
        color: var(--text);
        margin-bottom: .5rem;
        flex: 1;
    }

    .company-email {
        color: var(--text-light);
        font-size: .9rem;
        margin-bottom: 1.5rem;
        display: flex;
        align-items: center;
        gap: .5rem;
    }

    .company-stats {
        display: grid;
        grid-template-columns: 1fr 1fr auto;
        gap: 1rem;
        align-items: center;
    }

    .stat-item {
        text-align: center;
    }

    .stat-number {
        font-size: 1.5rem;
        font-weight: 700;
        color: var(--primary-light);
        display: block;
    }

    .stat-text {
        font-size: .8rem;
        color: var(--text-lighter);
        text-transform: uppercase;
        letter-spacing: .5px;
    }

    .view-btn,
    .users-btn {
        background: linear-gradient(135deg, var(--primary), var(--primary-light));
        color: white;
        border: none;
        border-radius: var(--radius-sm);
        padding: .75rem 1rem;
        font-size: .9rem;
        font-weight: 500;
        cursor: pointer;
        transition: var(--transition);
        text-decoration: none;
        display: inline-flex;
        align-items: center;
        gap: .5rem;
    }

    .view-btn:hover,
    .users-btn:hover {
        transform: translateY(-2px);
        box-shadow: 0 8px 20px rgba(124, 58, 237, .4);
    }

    .users-btn {
        background: linear-gradient(135deg, var(--warning), #fbbf24);
    }

    .users-btn:hover {
        box-shadow: 0 8px 20px rgba(245, 158, 11, .4);
    }

    .conversion-rate {
        margin-top: 1rem;
        padding-top: 1rem;
        border-top: 1px solid var(--border);
    }

    .progress-label {
        display: flex;
        justify-content: space-between;
        margin-bottom: .5rem;
        font-size: .85rem;
        color: var(--text-light);
    }

    .progress-bar {
        width: 100%;
        height: 6px;
        background: rgba(255, 255, 255, .1);
        border-radius: 3px;
        overflow: hidden;
    }

    .progress-fill {
        height: 100%;
        background: linear-gradient(90deg, var(--success), var(--secondary));
        border-radius: 3px;
        width: 0%;
        transition: width 1.2s ease-out;
    }

    .empty-state {
        text-align: center;
        padding: 3rem 1rem;
        color: var(--text-lighter);
    }

    .empty-state i {
        font-size: 3rem;
        margin-bottom: 1rem;
        opacity: .5;
    }

    @keyframes fadeInUp {
        from {
            opacity: 0;
            transform: translateY(30px);
        }

        to {
            opacity: 1;
            transform: translateY(0);
        }
    }

    .fade-in-up {
        opacity: 0;
        animation: fadeInUp .6s ease-out forwards;
    }

    ::-webkit-scrollbar {
        width: 8px;
    }

    ::-webkit-scrollbar-track {
        background: rgba(255, 255, 255, .1);
        border-radius: 4px;
    }

    ::-webkit-scrollbar-thumb {
        background: var(--primary);
        border-radius: 4px;
    }

    ::-webkit-scrollbar-thumb:hover {
        background: var(--primary-light);
    }

    @media(max-width:1024px) {
        .container {
            padding: 1.5rem;
        }

        .header h1 {
            font-size: 2.5rem;
        }

        .companies-grid {
            grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
        }
    }

    @media(max-width:768px) {
        .header h1 {
            font-size: 2rem;
        }

        .section-header {
            flex-direction: column;
            align-items: stretch;
        }

        .search-box {
            max-width: 100%;
        }

        .stats-grid {
            grid-template-columns: 1fr;
        }

        .company-stats {
            grid-template-columns: 1fr;
            gap: .75rem;
        }

        .view-btn,
        .users-btn {
            justify-content: center;
        }
    }

    @media(max-width:480px) {
        .container {
            padding: 1rem;
        }

        .header h1 {
            font-size: 1.75rem;
        }

        .stat-card,
        .company-card {
            padding: 1.5rem;
        }
    }
    .add-company-card{
        padding: 2rem;
        background: var(--card-bg);
        backdrop-filter: blur(20px);
        border: 1px solid var(--border);
        border-radius: var(--radius);
        text-align: center;
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;
        gap: 1rem;
    }
    .add-company{
        background: var(--card-bg);
        backdrop-filter: blur(20px);
        border: 1px solid var(--border);
        border-radius: var(--radius);
        padding: 2rem;
        transition: var(--transition);
        cursor: pointer;
        position: relative;
        overflow: hidden;
        color: var(--text);
        text-decoration: none;
        display: inline-flex;
        align-items: center;
        gap: .5rem;

    }
    .add-company::before{
        content: '';
        position: absolute;
        top: 0;
        left: -100%;
        width: 100%;
        height: 100%;
        background: linear-gradient(90deg, transparent, rgba(255,255,255,0.2), transparent);
        transition: left 0.5s;
    }
    .add-company:hover::before{
        left: 100%;
    }
    .add-company:hover{
        transform: translateY(-2px);
        box-shadow: 0 10px 25px rgba(124,58,237,0.4);
    }
    .user-btn{
        display: flex;
        gap: 1rem;
        align-items: center;
        justify-content: end;
    }
    </style>
</head>

<body>

    <div class="background">
        <div class="gradient-orb orb-1"></div>
        <div class="gradient-orb orb-2"></div>
    </div>

    <div class="container">

        <!-- Back to Global Admin Dashboard -->
        <?php if ($impersonating): ?>
        <div style="margin-bottom:1.5rem;text-align:right;">
            <a href="admin-dashboard.php" class="btn" style="background:var(--danger);">
                Back to Admin Dashboard
            </a>
        </div>
        <?php endif; ?>
         <div class="user-btn fade-in-up">
                
                <a href="../reports/purchase-report.php" class="users-btn">
                                Purchase Reports
                    </a>
                <a href="admin-user-management.php?id=<?= $c['id'] ?>" class="users-btn">
                                User Management
                    </a>                 
                    <a href="../backup.php" class="users-btn" style="background:var(--success);">
                                Backup
                    </a>
                    <a href="../logout.php" class="users-btn" style="background:var(--danger);">
                                Logout
                    </a>
         </div>   
        <!-- Header -->
        <div class="header fade-in-up">
            <h1>Admin Dashboard</h1>
            <p>Global overview of all companies and leads</p>
        </div>

        <!-- Global "Manage Users" Button (only when impersonating) -->
        <?php if ($impersonating): ?>
        <div style="margin-bottom:2rem;text-align:center;">
            <a href="admin-user-management.php?id=<?= $impersonated_id ?>" class="btn btn-primary"
                style="font-size:1.1rem;padding:1rem 2rem;">
                Manage Users for This Company
            </a>
        </div>
        <?php endif; ?>

         <!-- Stats -->
        <div class="stats-grid">
            <div class="stat-card fade-in-up" style="animation-delay: 0.1s">
                <div class="stat-icon"><i class="fas fa-building"></i></div>
                <div class="stat-value"><?= $totalCompanies ?></div>
                <div class="stat-label">Total Companies</div>
            </div>
            <div class="stat-card fade-in-up" style="animation-delay: 0.2s">
                <div class="stat-icon"><i class="fas fa-users"></i></div>
                <div class="stat-value"><?= $totalLeads ?></div>
                <div class="stat-label">Total Leads</div>
            </div>
            <div class="stat-card fade-in-up" style="animation-delay: 0.3s">
                <div class="stat-icon"><i class="fas fa-check-circle"></i></div>
                <div class="stat-value"><?= $convertedLeads ?></div>
                <div class="stat-label">Converted</div>
            </div>
            <div class="stat-card fade-in-up" style="animation-delay: 0.4s">
                <div class="stat-icon"><i class="fas fa-clock"></i></div>
                <div class="stat-value"><?= $pendingLeads ?></div>
                <div class="stat-label">Pending</div>
            </div>
        </div>

        <!-- Companies List -->
        <div class="companies-section">
            <div class="section-header">
                <h2 class="section-title">All Companies</h2>
                <div class="search-box">
                    <i class="fas fa-search search-icon"></i>
                    <input type="text" class="search-input" placeholder="Search companies..." id="searchInput">
                    <small class="search-hint">Press / to focus</small>
                </div>
                <button class="refresh-btn" onclick="location.reload()">
                    Refresh
                </button>
                
                   
                
            </div>

            <div class="companies-grid" id="companiesGrid">
                <?php if (empty($companies)): ?>
                <div class="empty-state">
                    <!-- <p>No companies found.</p> -->
                     <div class="company-card fade-in-up" style="animation-delay:<?= 0.1 + ($i * 0.05) ?>s"
                    data-company="<?= htmlspecialchars(json_encode($c), ENT_QUOTES) ?>">

                     </div>
                </div>
                <?php else: ?>
                <?php foreach ($companies as $i => $c): 
                $rate = $c['total_leads'] > 0 ? round(($c['converted_leads'] / $c['total_leads']) * 100, 1) : 0;
            ?>
                <div class="company-card fade-in-up" style="animation-delay:<?= 0.1 + ($i * 0.05) ?>s"
                    data-company="<?= htmlspecialchars(json_encode($c), ENT_QUOTES) ?>">
                    <div class="company-header">
                        <div>
                            <div class="company-name"><?= htmlspecialchars($c['company_name']) ?></div>
                            <div class="company-email">
                                Email: <?= htmlspecialchars($c['company_email']) ?>
                            </div>
                        </div>
                    </div>

                    <div class="company-stats">
                        <div class="stat-item">
                            <span class="stat-number"><?= $c['total_leads'] ?></span>
                            <span class="stat-text">Leads</span>
                        </div>
                        <div class="stat-item">
                            <span class="stat-number"><?= $c['converted_leads'] ?></span>
                            <span class="stat-text">Converted</span>
                        </div>
                        <div style="display:flex;gap:.5rem;flex-wrap:wrap;">
                            <a href="../dashboard.php?id=<?= $c['id'] ?>" class="view-btn">
                                View
                            </a>
                            <!-- <a href="admin-user-management.php?id=<?= $c['id'] ?>" class="users-btn">
                                Users
                            </a> -->
                        </div>
                    </div>

                    <?php if ($c['total_leads'] > 0): ?>
                    <div class="conversion-rate">
                        <div class="progress-label">
                            <span>Conversion Rate</span>
                            <span><?= $rate ?>%</span>
                        </div>
                        <div class="progress-bar">
                            <div class="progress-fill" data-width="<?= $rate ?>%"></div>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
                <?php endforeach; ?>
                <?php endif; ?>
                <div class="company-card fade-in-up add-company-card">
                    <a href="../company/company-management.php">
                          <div class="company-header add-company">
                                <i class="fas fa-plus"></i>
                                <div class="company-name">Add New Company</div>
                          </div>   
                        </a>
                </div>
            </div>

            
        </div>
    </div>

    <script>
    // Search
    const searchInput = document.getElementById('searchInput');
    const cards = document.querySelectorAll('.company-card');
    searchInput.addEventListener('input', () => {
        const term = searchInput.value.toLowerCase();
        cards.forEach(card => {
            const data = JSON.parse(card.dataset.company);
            const match = data.company_name.toLowerCase().includes(term) ||
                data.company_email.toLowerCase().includes(term);
            card.style.display = match ? 'block' : 'none';
        });
    });

    // Progress bars
    new IntersectionObserver((entries) => {
        entries.forEach(e => {
            if (e.isIntersecting) {
                e.target.style.width = e.target.dataset.width;
            }
        });
    }, {
        threshold: 0.5
    }).observeAll(document.querySelectorAll('.progress-fill'));

    // Keyboard shortcut
    document.addEventListener('keydown', e => {
        if (e.key === '/' && e.target.tagName !== 'INPUT') {
            e.preventDefault();
            searchInput.focus();
        }
    });
    </script>
</body>

</html>