<?php
session_start();
require_once "config/database.php";

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

$database = new Database();
$db = $database->getConnection();

if (!$db) {
    die("Database connection failed.");
}

try {
    $stmt = $db->query("
        SELECT c.*,
               (
                   SELECT COUNT(*)
                   FROM company_users cu
                   WHERE cu.company_id = c.id
               ) AS total_users
        FROM companies c
        ORDER BY c.id DESC
    ");
    $companies = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    die("Query error: " . $e->getMessage());
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Companies</title>
    <link rel="stylesheet" href="/dms/assets/css/app.css">
</head>
<body>
<style>
    .admin-table th:last-child,
.admin-table td:last-child {
    width: 72px;
    min-width: 72px;
    text-align: center;
    white-space: nowrap;
}

.actions-cell {
    padding-left: 8px !important;
    padding-right: 8px !important;
}

.dropdown {
    position: relative;
    display: inline-block;
}

.dropdown-toggle {
    width: 34px;
    height: 34px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    border: none;
    border-radius: 10px;
    background: #f1f5f9;
    font-size: 20px;
    cursor: pointer;
    opacity: 0.65;
    transition: all 0.2s ease;
}

.admin-table tbody tr:hover .dropdown-toggle {
    opacity: 1;
    background: #e2e8f0;
}

.dropdown-menu {
    position: absolute;
    top: calc(100% + 8px);
    right: 0;
    min-width: 180px;
    background: #fff;
    border: 1px solid #e5e7eb;
    border-radius: 12px;
    box-shadow: 0 10px 20px rgba(0,0,0,0.08);
    display: none;
    z-index: 999;
}

.dropdown-menu a {
    display: block;
    padding: 10px 14px;
    font-size: 13px;
    text-decoration: none;
    color: #111827;
}

.dropdown-menu a:hover {
    background: #f9fafb;
}
</style>


<div class="layout">
    <?php include 'nav.php'; ?>

    <main class="main">
        <div class="hero">
            <div class="hero-top">
                <div>
                    <h1>Companies</h1>
                    <p>Manage company workspaces and members.</p>
                </div>
                <div class="welcome-badge">
                    <?php echo htmlspecialchars($_SESSION['full_name'] ?? 'User'); ?>
                </div>
            </div>
        </div>

        <div class="card">
            <div style="display:flex; justify-content:space-between; align-items:center; gap:12px; flex-wrap:wrap; margin-bottom:12px;">
                <div>
                    <div class="section-title">Company List</div>
                    <div class="section-subtext">
                        Total: <strong><?php echo count($companies); ?></strong> company(s)
                    </div>
                </div>

                <a href="/dms/create_company.php" class="btn btn-primary">+ Create Company</a>
            </div>

            <?php if (isset($_GET['created']) && $_GET['created'] == 1): ?>
                <div class="badge success" style="display:block; margin-bottom:12px;">
                    Company created successfully.
                </div>
            <?php endif; ?>

            <?php if (isset($_GET['updated']) && $_GET['updated'] == 1): ?>
                <div class="badge success" style="display:block; margin-bottom:12px;">
                    Company updated successfully.
                </div>
            <?php endif; ?>

            <?php if (isset($_GET['deleted']) && $_GET['deleted'] == 1): ?>
                <div class="badge success" style="display:block; margin-bottom:12px;">
                    Company deleted successfully.
                </div>
            <?php endif; ?>

            <div class="table-wrap">
                <table class="admin-table">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Company Name</th>
                            <th>Code</th>
                            <th>Email</th>
                            <th>Phone</th>
                            <th>Members</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php if (!empty($companies)): ?>
                        <?php foreach ($companies as $row): ?>
                            <tr>
                                <td>
                                    <span class="chip">
                                        #<?php echo (int)$row['id']; ?>
                                    </span>
                                </td>
                                <td><?php echo htmlspecialchars($row['company_name'] ?? '-'); ?></td>
                                <td><?php echo htmlspecialchars($row['company_code'] ?? '-'); ?></td>
                                <td><?php echo htmlspecialchars($row['email'] ?? '-'); ?></td>
                                <td><?php echo htmlspecialchars($row['phone'] ?? '-'); ?></td>
                                <td>
                                    <span class="badge info">
                                        <?php echo (int)$row['total_users']; ?> user(s)
                                    </span>
                                </td>
                                <td class="actions-cell">
                                    <div class="dropdown">
                                        <button type="button" class="dropdown-toggle">⋮</button>

                                        <div class="dropdown-menu">
                                            <a href="/dms/edit_company.php?id=<?php echo (int)$row['id']; ?>">
                                                ✏️ Edit Company
                                            </a>

                                            <a href="/dms/add_user_to_company.php?company_id=<?php echo (int)$row['id']; ?>">
                                                👥 Manage Users
                                            </a>
                                            <a class="danger"
                                                href="/dms/delete_company.php?id=<?php echo (int)$row['id']; ?>"
                                                onclick="return confirm('Delete this company?');">
                                                🗑️ Delete
                                            </a>
                                        </div>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="7">
                                <div class="empty-state">No companies found.</div>
                            </td>
                        </tr>
                    <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </main>
</div>
<script>
document.addEventListener('click', function (e) {
    document.querySelectorAll('.dropdown').forEach(function (drop) {
        const menu = drop.querySelector('.dropdown-menu');
        const button = drop.querySelector('.dropdown-toggle');

        if (drop.contains(e.target)) {
            if (e.target === button || button.contains(e.target)) {
                const isOpen = menu.style.display === 'block';

                document.querySelectorAll('.dropdown-menu').forEach(function (m) {
                    m.style.display = 'none';
                });

                menu.style.display = isOpen ? 'none' : 'block';
            }
        } else {
            menu.style.display = 'none';
        }
    });
});
</script>
</body>
</html>