<?php
session_start();
require_once 'database.php';

// Initialize database
try {
    $database = new Database();
    
    // Create tables if they don't exist
    if (!$database->table_exists('whistleblowing_companies')) {
        $database->create_whistleblowing_tables();
    }
    
    // Get query parameters
    $page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
    $category = isset($_GET['category']) ? $_GET['category'] : null;
    $search = isset($_GET['search']) ? trim($_GET['search']) : '';
    $per_page = 24; // 4 rows of 6 cards each
    
    // Get companies
    if ($search) {
        $companies = $database->search_companies($search, $category, $page, $per_page);
        $total_companies = $database->get_search_count($search, $category);
    } else {
        $companies = $database->get_all_companies($page, $per_page, $category);
        $total_companies = $database->get_total_companies_count($category);
    }
    
    $total_pages = ceil($total_companies / $per_page);
    
    // Get category counts
    $category_counts = $database->get_company_counts_by_category();
    
} catch (Exception $e) {
    error_log("Database error: " . $e->getMessage());
    $companies = [];
    $category_counts = [];
    $total_pages = 1;
}
?>

<!DOCTYPE html>
<html lang="zxx">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    
    <!-- Link of CSS files -->
    <link rel="stylesheet" href="assets/css/animate.min.css">
    <link rel="stylesheet" href="assets/css/bootstrap.min.css">
    <link rel="stylesheet" href="assets/css/fontawsome.min.css">
    <link rel="stylesheet" href="assets/fonts/flaticon.css">
    <link rel="stylesheet" href="assets/css/meanmenu.min.css">
    <link rel="stylesheet" href="assets/css/owl.carousel.min.css">
    <link rel="stylesheet" href="assets/css/nice-select.min.css">
    <link rel="stylesheet" href="assets/css/owl.theme.default.min.css">
    <link rel="stylesheet" href="assets/css/magnific-popup.min.css">
    <link rel="stylesheet" href="assets/css/jquery-ui.min.css">
    <link rel="stylesheet" href="assets/css/odometer.min.css">
    <link rel="stylesheet" href="assets/css/barfiller.css">
    <link rel="stylesheet" href="assets/css/style.css">
    <link rel="stylesheet" href="assets/css/dark.css">
    <link rel="stylesheet" href="assets/css/responsive.css">
    
    <title>Whistleblowing Companies Database | Reclaim Ethically</title>
    <link rel="icon" type="image/png" href="assets/images/fav-icon.png">
    
    <style>
        :root {
            --primary-green: #1a5d1a;
            --secondary-green: #2e7d32;
            --light-green: #e8f5e9;
            --dark-green: #0d3b0d;
        }
        
        .database-hero {
            background: linear-gradient(135deg, var(--dark-green) 0%, var(--primary-green) 100%);
            color: white;
            padding: 80px 0 60px;
        }
        
        .database-filters {
            background: white;
            padding: 30px;
            border-radius: 12px;
            box-shadow: 0 5px 20px rgba(0,0,0,0.05);
            margin-bottom: 30px;
        }
        
        .company-card-large {
            background: white;
            border-radius: 12px;
            overflow: hidden;
            box-shadow: 0 5px 15px rgba(0,0,0,0.05);
            transition: all 0.3s ease;
            height: 100%;
            border: 1px solid #e0e0e0;
        }
        
        .company-card-large:hover {
            transform: translateY(-5px);
            box-shadow: 0 15px 30px rgba(0,0,0,0.1);
            border-color: var(--primary-green);
        }
        
        .risk-badge {
            position: absolute;
            top: 15px;
            right: 15px;
            padding: 5px 15px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
            text-transform: uppercase;
        }
        
        .risk-high { background: #dc3545; color: white; }
        .risk-medium { background: #ffc107; color: #212529; }
        .risk-low { background: #28a745; color: white; }
        .risk-extreme { background: #6f42c1; color: white; }
        
        .category-filter {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
            margin-bottom: 20px;
        }
        
        .category-btn {
            padding: 10px 20px;
            border: 2px solid #e0e0e0;
            background: white;
            border-radius: 25px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .category-btn.active {
            background: var(--primary-green);
            color: white;
            border-color: var(--primary-green);
        }
        
        .category-btn:hover:not(.active) {
            border-color: var(--primary-green);
            color: var(--primary-green);
        }
        
        .pagination-container {
            display: flex;
            justify-content: center;
            margin-top: 40px;
        }
        
        .stats-card {
            background: white;
            padding: 25px;
            border-radius: 10px;
            text-align: center;
            box-shadow: 0 5px 15px rgba(0,0,0,0.05);
            margin-bottom: 20px;
        }
        
        .stats-number {
            font-size: 36px;
            font-weight: 800;
            color: var(--dark-green);
            margin-bottom: 10px;
        }
        
        .stats-label {
            color: #666;
            font-size: 14px;
            text-transform: uppercase;
            letter-spacing: 1px;
        }
    </style>
</head>
<body>
    
    <div class="theme-switcher">
        <label id="switch" class="switch">
            <input type="checkbox" onchange="toggleTheme()" id="slider">
            <span class="slider round"></span>
        </label>
    </div>
    
    <!-- Navigation -->
    <?php $page = 'whistleblowing'; include 'header.php'; ?>
    
    <!-- Hero Section -->
    <section class="database-hero">
        <div class="container">
            <div class="row align-items-center">
                <div class="col-lg-8">
                    <h1 class="display-4 fw-bold text-white mb-3">Companies Database</h1>
                    <p class="lead text-white mb-0">Browse 100+ companies reported for fraud, scams, and misconduct</p>
                </div>
                <div class="col-lg-4 text-lg-end">
                    <div class="text-white">
                        <div class="h2 fw-bold"><?php echo number_format($total_companies); ?></div>
                        <p class="mb-0">Companies Tracked</p>
                    </div>
                </div>
            </div>
        </div>
    </section>
    
    <!-- Stats Section -->
    <section class="py-5 bg-light">
        <div class="container">
            <div class="row">
                <div class="col-md-3 col-6">
                    <div class="stats-card">
                        <div class="stats-number"><?php echo number_format($total_companies); ?></div>
                        <div class="stats-label">Total Companies</div>
                    </div>
                </div>
                <div class="col-md-3 col-6">
                    <div class="stats-card">
                        <div class="stats-number">1,247</div>
                        <div class="stats-label">Reports Filed</div>
                    </div>
                </div>
                <div class="col-md-3 col-6">
                    <div class="stats-card">
                        <div class="stats-number">387</div>
                        <div class="stats-label">Legal Actions</div>
                    </div>
                </div>
                <div class="col-md-3 col-6">
                    <div class="stats-card">
                        <div class="stats-number">$2.1B</div>
                        <div class="stats-label">Fraud Prevented</div>
                    </div>
                </div>
            </div>
        </div>
    </section>
    
    <!-- Main Database Section -->
    <section class="py-5">
        <div class="container">
            <!-- Filters -->
            <div class="database-filters">
                <form id="databaseFilterForm" method="GET" action="">
                    <div class="row">
                        <div class="col-md-8 mb-3">
                            <div class="input-group">
                                <input type="text" 
                                       class="form-control form-control-lg" 
                                       name="search" 
                                       placeholder="Search companies by name, industry, or description..."
                                       value="<?php echo htmlspecialchars($search); ?>">
                                <button class="btn btn-primary btn-lg" type="submit">
                                    <i class="fas fa-search"></i>
                                </button>
                            </div>
                        </div>
                        <div class="col-md-4 mb-3">
                            <select class="form-control form-control-lg" name="category" onchange="this.form.submit()">
                                <option value="">All Categories</option>
                                <option value="crypto" <?php echo $category == 'crypto' ? 'selected' : ''; ?>>Cryptocurrency Scams</option>
                                <option value="finance" <?php echo $category == 'finance' ? 'selected' : ''; ?>>Financial Fraud</option>
                                <option value="forex" <?php echo $category == 'forex' ? 'selected' : ''; ?>>Forex/Investment Scams</option>
                                <option value="consumer" <?php echo $category == 'consumer' ? 'selected' : ''; ?>>Consumer Fraud</option>
                            </select>
                        </div>
                    </div>
                    
                    <!-- Quick Category Filters -->
                    <div class="category-filter">
                        <button type="button" class="category-btn <?php echo !$category ? 'active' : ''; ?>" 
                                onclick="window.location.href='?search=<?php echo urlencode($search); ?>'">
                            All (<?php echo $total_companies; ?>)
                        </button>
                        <?php foreach ($category_counts as $cat): ?>
                            <button type="button" class="category-btn <?php echo $category == $cat['category'] ? 'active' : ''; ?>"
                                    onclick="window.location.href='?category=<?php echo $cat['category']; ?>&search=<?php echo urlencode($search); ?>'">
                                <?php 
                                    $cat_name = ucfirst($cat['category']);
                                    if ($cat['category'] == 'crypto') $cat_name = 'Crypto';
                                    elseif ($cat['category'] == 'forex') $cat_name = 'Forex';
                                    echo $cat_name . ' (' . $cat['count'] . ')';
                                ?>
                            </button>
                        <?php endforeach; ?>
                    </div>
                </form>
                
                <?php if ($search): ?>
                    <div class="alert alert-info mt-3">
                        <i class="fas fa-info-circle me-2"></i>
                        Found <?php echo count($companies); ?> companies matching "<?php echo htmlspecialchars($search); ?>"
                        <a href="?" class="float-end">Clear search</a>
                    </div>
                <?php endif; ?>
            </div>
            
            <!-- Companies Grid -->
            <div class="row">
                <?php if (empty($companies)): ?>
                    <div class="col-12 text-center py-5">
                        <i class="fas fa-search fa-4x text-muted mb-3"></i>
                        <h3>No companies found</h3>
                        <p class="text-muted">Try adjusting your search or filter criteria</p>
                        <a href="?" class="btn btn-primary">View All Companies</a>
                    </div>
                <?php else: ?>
                    <?php foreach ($companies as $company): ?>
                        <div class="col-lg-4 col-md-6 mb-4">
                            <div class="company-card-large">
                                <div class="position-relative">
                                    <div class="company-header p-4" 
                                         style="background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);">
                                        <div class="d-flex align-items-center">
                                            <div class="company-logo me-3" 
                                                 style="width: 50px; height: 50px; background: white; 
                                                        border-radius: 10px; display: flex; align-items: center; 
                                                        justify-content: center; font-weight: bold; color: var(--dark-green); 
                                                        border: 2px solid #e0e0e0;">
                                                <?php echo substr($company['short_name'] ?: $company['name'], 0, 2); ?>
                                            </div>
                                            <div style="flex: 1; min-width: 0;">
                                                <h5 class="mb-1 text-truncate"><?php echo htmlspecialchars($company['name']); ?></h5>
                                                <p class="text-muted mb-0 small">
                                                    <i class="fas fa-industry me-1"></i>
                                                    <?php echo htmlspecialchars($company['industry']); ?>
                                                </p>
                                            </div>
                                        </div>
                                    </div>
                                    <span class="risk-badge risk-<?php echo $company['risk_level']; ?>">
                                        <?php echo ucfirst($company['risk_level']); ?>
                                    </span>
                                </div>
                                
                                <div class="company-body p-4">
                                    <div class="mb-3">
                                        <small class="text-muted d-block mb-2">Primary Allegations:</small>
                                        <div class="d-flex flex-wrap gap-2">
                                            <?php 
                                            $allegations = is_array($company['allegations']) ? $company['allegations'] : [];
                                            foreach (array_slice($allegations, 0, 3) as $allegation): ?>
                                                <span class="badge bg-danger bg-opacity-10 text-danger">
                                                    <?php echo htmlspecialchars($allegation); ?>
                                                </span>
                                            <?php endforeach; ?>
                                            <?php if (count($allegations) > 3): ?>
                                                <span class="badge bg-secondary">+<?php echo count($allegations) - 3; ?> more</span>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                    
                                    <p class="text-muted small mb-3" style="height: 60px; overflow: hidden;">
                                        <?php echo htmlspecialchars(substr($company['description'], 0, 150)); ?>
                                        <?php if (strlen($company['description']) > 150): ?>...<?php endif; ?>
                                    </p>
                                    
                                    <div class="row g-2 mb-3">
                                        <div class="col-6">
                                            <div class="text-center p-2 bg-light rounded">
                                                <div class="fw-bold text-primary"><?php echo number_format($company['reports_count']); ?></div>
                                                <small class="text-muted">Reports</small>
                                            </div>
                                        </div>
                                        <div class="col-6">
                                            <div class="text-center p-2 bg-light rounded">
                                                <div class="fw-bold text-danger"><?php echo htmlspecialchars($company['estimated_losses'] ?: 'N/A'); ?></div>
                                                <small class="text-muted">Losses</small>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="d-flex justify-content-between align-items-center mt-3">
                                        <small class="text-muted">
                                            <i class="fas fa-clock me-1"></i>
                                            Last report: <?php echo $company['last_report_date'] ? date('M d, Y', strtotime($company['last_report_date'])) : 'N/A'; ?>
                                        </small>
                                        <span class="badge bg-secondary">
                                            <?php echo ucfirst($company['category']); ?>
                                        </span>
                                    </div>
                                    
                                    <a href="company-details.php?id=<?php echo urlencode($company['company_id']); ?>" 
                                       class="btn btn-primary w-100 mt-3">
                                        <i class="fas fa-eye me-2"></i> View Details
                                    </a>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
            
            <!-- Pagination -->
            <?php if ($total_pages > 1): ?>
                <div class="pagination-container">
                    <nav aria-label="Page navigation">
                        <ul class="pagination">
                            <li class="page-item <?php echo $page <= 1 ? 'disabled' : ''; ?>">
                                <a class="page-link" href="?page=<?php echo $page-1; ?>&category=<?php echo $category; ?>&search=<?php echo urlencode($search); ?>">
                                    <i class="fas fa-chevron-left"></i>
                                </a>
                            </li>
                            
                            <?php for ($i = 1; $i <= min($total_pages, 5); $i++): ?>
                                <li class="page-item <?php echo $i == $page ? 'active' : ''; ?>">
                                    <a class="page-link" href="?page=<?php echo $i; ?>&category=<?php echo $category; ?>&search=<?php echo urlencode($search); ?>">
                                        <?php echo $i; ?>
                                    </a>
                                </li>
                            <?php endfor; ?>
                            
                            <?php if ($total_pages > 5): ?>
                                <li class="page-item disabled">
                                    <span class="page-link">...</span>
                                </li>
                                <li class="page-item">
                                    <a class="page-link" href="?page=<?php echo $total_pages; ?>&category=<?php echo $category; ?>&search=<?php echo urlencode($search); ?>">
                                        <?php echo $total_pages; ?>
                                    </a>
                                </li>
                            <?php endif; ?>
                            
                            <li class="page-item <?php echo $page >= $total_pages ? 'disabled' : ''; ?>">
                                <a class="page-link" href="?page=<?php echo $page+1; ?>&category=<?php echo $category; ?>&search=<?php echo urlencode($search); ?>">
                                    <i class="fas fa-chevron-right"></i>
                                </a>
                            </li>
                        </ul>
                    </nav>
                </div>
            <?php endif; ?>
            
            <!-- Database Info -->
            <div class="alert alert-light mt-4">
                <div class="row align-items-center">
                    <div class="col-md-8">
                        <h5 class="mb-1"><i class="fas fa-database me-2"></i> Database Information</h5>
                        <p class="mb-0 text-muted">This database contains information on 100+ companies reported for fraud, scams, and misconduct.</p>
                    </div>
                    <div class="col-md-4 text-md-end">
                        <button class="btn btn-outline-primary" onclick="exportDatabase()">
                            <i class="fas fa-download me-2"></i> Export Data
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </section>
    
    <!-- Footer -->
    <?php include 'footer.php'; ?>
    
    <!-- Scripts -->
    <script src="assets/js/jquery.min.js"></script>
    <script src="assets/js/bootstrap.bundle.min.js"></script>
    
    <script>
    function exportDatabase() {
        // You would implement actual export functionality here
        alert('Export functionality would be implemented here. Could export to CSV, PDF, or Excel.');
    }
    
    // Real-time search
    let searchTimeout;
    document.querySelector('input[name="search"]').addEventListener('input', function(e) {
        clearTimeout(searchTimeout);
        searchTimeout = setTimeout(() => {
            if (e.target.value.length >= 2 || e.target.value.length === 0) {
                document.getElementById('databaseFilterForm').submit();
            }
        }, 500);
    });
    
    // Category filter buttons
    document.querySelectorAll('.category-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            document.querySelectorAll('.category-btn').forEach(b => b.classList.remove('active'));
            this.classList.add('active');
        });
    });
    </script>
</body>
</html>