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

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

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

// === AJAX DELETE HANDLER ===
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'delete') {
    header('Content-Type: application/json');
    $id = (int)$_POST['id'];
    $stmt = $conn->prepare("DELETE FROM companies WHERE id = ?");
    $stmt->bind_param('i', $id);
    $success = $stmt->execute();
    $stmt->close();
    echo json_encode(['success' => $success]);
    exit;
}

// === PAGINATION & SEARCH ===
$limit = 10;
$page = max(1, (int)($_GET['page'] ?? 1));
$offset = ($page - 1) * $limit;
$search = trim($_GET['search'] ?? '');

$where = $search ? "WHERE company_name LIKE ? OR company_email LIKE ? OR company_phone LIKE ?" : '';
$param = $search ? "%$search%" : '';
$types = $search ? 'sss' : '';

// Count
$countSql = "SELECT COUNT(*) FROM companies $where";
$stmt = $conn->prepare($countSql);
if ($search) $stmt->bind_param($types, $param, $param, $param);
$stmt->execute();
$stmt->bind_result($total);
$stmt->fetch();
$stmt->close();
$totalPages = ceil($total / $limit);

// Fetch
$sql = "SELECT id, company_name, company_email, company_phone, company_address, created_at 
        FROM companies $where 
        ORDER BY created_at DESC 
        LIMIT ? OFFSET ?";
$stmt = $conn->prepare($sql);
if ($search) {
    $stmt->bind_param($types . 'ii', $param, $param, $param, $limit, $offset);
} else {
    $stmt->bind_param('ii', $limit, $offset);
}
$stmt->execute();
$result = $stmt->get_result();
$companies = $result->fetch_all(MYSQLI_ASSOC);
$stmt->close();
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Company Management</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;
        --secondary: #06b6d4;
        --success: #10b981;
        --danger: #ef4444;
        --dark: #0f172a;
        --darker: #020617;
        --card-bg: rgba(255, 255, 255, .08);
        --border: rgba(255, 255, 255, .1);
        --text: #f1f5f9;
        --text-light: #cbd5e1;
        --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;
    }

    .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 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 {

        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: 1200px;
        margin: 2rem auto;
        padding: 0 1.5rem;
    }

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

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

    .search-box {
        position: relative;
        max-width: 320px;
        flex: 1;
    }

    .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);
        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-light);
    }

    .table-container {
        background: var(--card-bg);
        backdrop-filter: blur(20px);
        border: 1px solid var(--border);
        border-radius: var(--radius);
        overflow: hidden;
        box-shadow: 0 20px 40px rgba(0, 0, 0, .3);
    }

    .table {
        width: 100%;
        border-collapse: collapse;
    }

    .table-header {
        background: linear-gradient(135deg, var(--primary), var(--primary-light));
    }

    .table th {
        padding: 1.25rem 1rem;
        text-align: left;
        font-weight: 600;
        color: #fff;
        font-size: .9rem;
        text-transform: uppercase;
        letter-spacing: .5px;
    }

    .table td {
        padding: 1.25rem 1rem;
        border-bottom: 1px solid var(--border);
        color: var(--text);
    }

    .table tbody tr {
        transition: var(--transition);
    }

    .table tbody tr:hover {
        background: rgba(255, 255, 255, .05);
        transform: translateX(5px);
    }

    .actions {
        display: flex;
        gap: .5rem;
        flex-wrap: wrap;
    }

    .btn-sm {
        padding: .4rem .8rem;
        border: none;
        border-radius: var(--radius-sm);
        font-size: .85rem;
        font-weight: 600;
        cursor: pointer;
        transition: var(--transition);
        display: inline-flex;
        align-items: center;
        gap: .4rem;
    }

    .btn-view {
        background: #3b82f6;
        color: white;
    }

    .btn-edit {
        background: var(--warning);
        color: white;
    }

    .btn-delete {
        background: var(--danger);
        color: white;
    }

    .btn-sm:hover {
        transform: scale(1.05);
        opacity: .9;
    }

    .pagination {
        display: flex;
        justify-content: center;
        gap: .5rem;
        padding: 2rem;
        flex-wrap: wrap;
    }

    .pagination a {
        min-width: 40px;
        height: 40px;
        padding: .5rem;
        background: var(--card-bg);
        color: var(--text);
        text-decoration: none;
        border-radius: var(--radius-sm);
        border: 1px solid var(--border);
        transition: var(--transition);
        font-weight: 500;
        display: inline-flex;
        align-items: center;
        justify-content: center;
    }

    .pagination a.active,
    .pagination a:hover {
        background: linear-gradient(135deg, var(--primary), var(--primary-light));
        color: #fff;
        border-color: transparent;
        transform: translateY(-2px);
    }

    .empty-state {
        text-align: center;
        padding: 4rem 2rem;
        color: var(--text-light);
    }

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

    /* ADD BUTTON (now a link) */
    .add-btn {
        position: fixed;
        bottom: 2rem;
        right: 2rem;
        width: 60px;
        height: 60px;
        background: linear-gradient(135deg, var(--primary), var(--primary-light));
        color: white;
        border: none;
        border-radius: 50%;
        font-size: 1.8rem;
        cursor: pointer;
        box-shadow: 0 10px 30px rgba(124, 58, 237, .4);
        transition: var(--transition);
        z-index: 1000;
        display: flex;
        align-items: center;
        justify-content: center;
        text-decoration: none;
    }

    .add-btn:hover {
        transform: scale(1.1) translateY(-4px);
        box-shadow: 0 15px 35px rgba(124, 58, 237, .5);
    }

    @media(max-width:768px) {
        .header {
            flex-direction: column;
            align-items: stretch;
        }

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

        .table-container {
            overflow-x: auto;
        }

        .table {
            min-width: 800px;
        }
    }
    .btn {
        display: inline-flex;
        align-items: center;
        gap: 0.5rem;
        padding: 0.875rem 1.5rem;
        border: none;
        border-radius: var(--radius-sm);
        font-weight: 600;
        font-size: 0.95rem;
        text-decoration: none;
        cursor: pointer;
        transition: var(--transition);
        position: relative;
        overflow: hidden;
    }

    .btn-primary {
        background: linear-gradient(135deg, var(--primary), var(--primary-light));
        color: white;
    }

    .btn-primary::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;
    }

    .btn-primary:hover::before {
        left: 100%;
    }

    .btn-primary:hover {
        transform: translateY(-2px);
        box-shadow: 0 10px 25px rgba(124, 58, 237, 0.4);
    }
    </style>
</head>

<body>

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

    <div class="container">
        <div class="header">
            <h1>Company Management</h1>
            <div class="search-box">
                <i class="fas fa-search search-icon"></i>
                <input type="text" id="searchInput" class="search-input" placeholder="Search companies..."
                    value="<?= htmlspecialchars($search) ?>">
            </div>
            <div style="margin-bottom: 1.5rem; text-align: right;">
            <a href="../admin/admin-dashboard.php" class="btn" style="background: var(--danger);">
                Back to Admin Dashboard
            </a>
        </div>
            
        </div>
        
        
     
        <div class="table-container">
            <?php if (empty($companies)): ?>
            <div class="empty-state">
                <h3>No companies found</h3>
                <p>Click the + button to add your first company.</p>
            </div>
            <?php else: ?>
            <table class="table">
                <thead class="table-header">
                    <tr>
                        <th>Name</th>
                        <th>Email</th>
                        <th>Phone</th>
                        <th>Created</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody id="companyTable">
                    <?php foreach ($companies as $c): ?>
                    <tr data-id="<?= $c['id'] ?>">
                        <td><?= htmlspecialchars($c['company_name']) ?></td>
                        <td><?= htmlspecialchars($c['company_email']) ?></td>
                        <td><?= htmlspecialchars($c['company_phone']) ?></td>
                        <td><?= date('M j, Y', strtotime($c['created_at'])) ?></td>
                        <td>
                            <div class="actions">
                                <a href="view-company.php?id=<?= $c['id'] ?>" class="btn-sm btn-view" title="View">
                                    View
                                </a>
                                <a href="edit-company.php?id=<?= $c['id'] ?>" class="btn-sm btn-edit" title="Edit">
                                    Edit
                                </a>
                                <button class="btn-sm btn-delete"
                                    onclick="deleteCompany(<?= $c['id'] ?>, '<?= addslashes(htmlspecialchars($c['company_name'])) ?>')"
                                    title="Delete">
                                    Delete
                                </button>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>

            <?php if ($totalPages > 1): ?>
            <div class="pagination">
                <?php
                $range = 2; $start = max(1, $page - $range); $end = min($totalPages, $page + $range);
                if ($start > 1): ?>
                <a href="?page=1&search=<?= urlencode($search) ?>">First</a>
                <?php endif;
                for ($i = $start; $i <= $end; $i++): ?>
                <a href="?page=<?= $i ?>&search=<?= urlencode($search) ?>" class="<?= $i == $page ? 'active' : '' ?>">
                    <?= $i ?>
                </a>
                <?php endfor;
                if ($end < $totalPages): ?>
                <a href="?page=<?= $totalPages ?>&search=<?= urlencode($search) ?>">Last</a>
                <?php endif; ?>
            </div>
            <?php endif; ?>
            <?php endif; ?>
        </div>
    </div>

    <!-- ADD COMPANY BUTTON (LINK) -->
    <a href="add-company.php" class="add-btn" title="Add Company">
        <i class="fas fa-plus"></i>
    </a>

    <script>
    let timeout;

    // Delete Company (AJAX)
    function deleteCompany(id, name) {
        if (!confirm(`Delete "${name}"? This cannot be undone.`)) return;
        const formData = new FormData();
        formData.append('action', 'delete');
        formData.append('id', id);

        fetch('', {
                method: 'POST',
                body: formData
            })
            .then(r => r.json())
            .then(data => {
                if (data.success) {
                    document.querySelector(`tr[data-id="${id}"]`).remove();
                }
            });
    }

    // Live Search
    document.getElementById('searchInput').addEventListener('input', function() {
        clearTimeout(timeout);
        timeout = setTimeout(() => {
            const q = this.value;
            const url = `?search=${encodeURIComponent(q)}`;
            history.replaceState(null, '', url);
            location.href = url;
        }, 500);
    });
    </script>
</body>

</html>