<?php
require_once __DIR__ . '/includes/config.php';
require_once 'db.php';
require_once __DIR__ . '/includes/permissions.php';
if (session_status() === PHP_SESSION_NONE) { session_start(); }

// Must be logged in
if (!isset($_SESSION['user_id'])) {
    header("Location: " . BASE_URL . "/login.php");
    exit;
}

$uid  = (int)$_SESSION['user_id'];
$role = $_SESSION['user_role'] ?? '';

// Handle company selection POST
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['company_id'])) {
    $chosen = (int)$_POST['company_id'];

    if ($role === 'admin') {
        // Admin can select any company
        $r = $conn->query("SELECT id FROM company_master WHERE id = $chosen LIMIT 1");
        if ($r && $r->num_rows > 0) {
            $_SESSION['active_company_id'] = $chosen;
            unset($_SESSION['permissions']); // reload for new company context
            loadPermissions($conn);
            header("Location: " . getDefaultLandingUrl());
            exit;
        }
    } else {
        // Staff: verify access
        $r = $conn->query("SELECT id FROM user_companies WHERE user_id = $uid AND company_id = $chosen LIMIT 1");
        if ($r && $r->num_rows > 0) {
            $_SESSION['active_company_id'] = $chosen;
            unset($_SESSION['permissions']); // reload for new company context
            loadPermissions($conn);
            header("Location: " . getDefaultLandingUrl());
            exit;
        }
    }
    $accessError = "You do not have access to that company.";
}

// Load companies available to this user
if ($role === 'admin') {
    $companies = $conn->query("SELECT * FROM company_master ORDER BY company_name ASC")->fetch_all(MYSQLI_ASSOC);
} else {
    $companies = $conn->query(
        "SELECT cm.* FROM company_master cm
         JOIN user_companies uc ON uc.company_id = cm.id
         WHERE uc.user_id = $uid
         ORDER BY cm.company_name ASC"
    )->fetch_all(MYSQLI_ASSOC);
}

// If only one company (edge case), just set it and redirect
if (count($companies) === 1) {
    $_SESSION['active_company_id'] = (int)$companies[0]['id'];
    loadPermissions($conn);
    header("Location: " . getDefaultLandingUrl());
    exit;
}

// If no companies at all
if (count($companies) === 0) {
    session_unset();
    session_destroy();
    header("Location: " . BASE_URL . "/login.php?no_company=1");
    exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Select Company — ERP System</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <link rel="stylesheet" href="<?= BASE_URL ?>/assets/css/style.css">
    <style>
        body.company-select-page {
            background: linear-gradient(135deg, #0f172a 0%, #1e293b 50%, #0f172a 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 24px;
        }
        .company-select-wrapper {
            width: 100%;
            max-width: 680px;
        }
        .company-select-header {
            text-align: center;
            margin-bottom: 32px;
        }
        .company-select-header .logo-icon {
            width: 64px;
            height: 64px;
            border-radius: 16px;
            background: var(--primary);
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 16px;
            font-size: 28px;
            color: #fff;
            box-shadow: 0 8px 24px rgba(37,99,235,0.35);
        }
        .company-select-header h1 {
            color: #fff;
            font-size: 24px;
            font-weight: 700;
            margin-bottom: 6px;
        }
        .company-select-header p {
            color: #94a3b8;
            font-size: 14px;
        }
        .company-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
            gap: 16px;
            margin-bottom: 24px;
        }
        .company-card {
            background: #fff;
            border-radius: 12px;
            padding: 0;
            overflow: hidden;
            box-shadow: 0 4px 16px rgba(0,0,0,0.18);
            transition: transform 0.15s ease, box-shadow 0.15s ease;
            cursor: pointer;
            border: 2px solid transparent;
            position: relative;
        }
        .company-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 24px rgba(0,0,0,0.25);
            border-color: var(--primary);
        }
        .company-card form {
            display: contents;
        }
        .company-card button {
            all: unset;
            display: block;
            width: 100%;
            cursor: pointer;
            padding: 20px;
            box-sizing: border-box;
        }
        .company-card-accent {
            height: 4px;
            background: linear-gradient(90deg, var(--primary), #6366f1);
        }
        .company-card-body {
            padding: 20px;
        }
        .company-card-logo {
            width: 48px;
            height: 48px;
            border-radius: 8px;
            object-fit: contain;
            border: 1px solid var(--border);
            margin-bottom: 12px;
            padding: 4px;
            background: #f8fafc;
        }
        .company-card-icon {
            width: 48px;
            height: 48px;
            border-radius: 8px;
            background: var(--primary-light);
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 20px;
            color: var(--primary);
            margin-bottom: 12px;
        }
        .company-card h3 {
            font-size: 15px;
            font-weight: 600;
            color: var(--text-primary);
            margin-bottom: 4px;
            line-height: 1.3;
        }
        .company-card-meta {
            font-size: 12px;
            color: var(--text-muted);
            display: flex;
            flex-direction: column;
            gap: 3px;
        }
        .company-card-meta span {
            display: flex;
            align-items: center;
            gap: 5px;
        }
        .company-card-meta i {
            width: 12px;
            color: var(--text-muted);
        }
        .company-card-default-badge {
            position: absolute;
            top: 14px;
            right: 14px;
            background: var(--primary);
            color: #fff;
            font-size: 10px;
            font-weight: 600;
            padding: 2px 7px;
            border-radius: 20px;
            letter-spacing: 0.5px;
        }
        .company-select-footer {
            text-align: center;
        }
        .company-select-footer a {
            color: #94a3b8;
            font-size: 13px;
            display: inline-flex;
            align-items: center;
            gap: 6px;
            transition: color 0.15s;
        }
        .company-select-footer a:hover {
            color: #fff;
        }
        .user-greeting {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            background: rgba(255,255,255,0.08);
            border: 1px solid rgba(255,255,255,0.1);
            border-radius: 24px;
            padding: 6px 14px;
            color: #cbd5e1;
            font-size: 13px;
            margin-bottom: 24px;
        }
        .user-greeting .avatar {
            width: 24px;
            height: 24px;
            border-radius: 50%;
            background: var(--primary);
            color: #fff;
            font-size: 11px;
            font-weight: 700;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .alert-cs {
            background: rgba(239,68,68,0.12);
            border: 1px solid rgba(239,68,68,0.3);
            color: #fca5a5;
            border-radius: 8px;
            padding: 10px 14px;
            font-size: 13px;
            margin-bottom: 16px;
            display: flex;
            align-items: center;
            gap: 8px;
        }
    </style>
</head>
<body class="company-select-page">

<div class="company-select-wrapper">

    <div class="company-select-header">
        <div class="logo-icon">
            <i class="fas fa-store-alt"></i>
        </div>
        <h1>Select Company</h1>
        <p>Choose a company to continue</p>
    </div>

    <div style="text-align:center;">
        <div class="user-greeting">
            <div class="avatar"><?= strtoupper(substr($_SESSION['user_name'] ?? 'U', 0, 1)) ?></div>
            Logged in as <strong><?= htmlspecialchars($_SESSION['user_name'] ?? '') ?></strong>
        </div>
    </div>

    <?php if (!empty($accessError)): ?>
    <div class="alert-cs">
        <i class="fas fa-exclamation-circle"></i>
        <?= htmlspecialchars($accessError) ?>
    </div>
    <?php endif; ?>

    <div class="company-grid">
        <?php foreach ($companies as $co): ?>
        <div class="company-card">
            <div class="company-card-accent"></div>
            <div class="company-card-body">
                <?php if (!empty($co['logo'])): ?>
                    <img src="<?= BASE_URL ?>/<?= htmlspecialchars($co['logo']) ?>" alt="" class="company-card-logo">
                <?php else: ?>
                    <div class="company-card-icon"><i class="fas fa-building"></i></div>
                <?php endif; ?>

                <?php if ($co['is_default']): ?>
                <span class="company-card-default-badge">Default</span>
                <?php endif; ?>

                <h3><?= htmlspecialchars($co['company_name']) ?></h3>

                <div class="company-card-meta">
                    <?php if (!empty($co['city']) || !empty($co['state'])): ?>
                    <span>
                        <i class="fas fa-map-marker-alt"></i>
                        <?= htmlspecialchars(implode(', ', array_filter([$co['city'], $co['state']]))) ?>
                    </span>
                    <?php endif; ?>
                    <?php if (!empty($co['gst_no'])): ?>
                    <span>
                        <i class="fas fa-id-badge"></i>
                        GST: <?= htmlspecialchars($co['gst_no']) ?>
                    </span>
                    <?php endif; ?>
                    <?php if (!empty($co['phone'])): ?>
                    <span>
                        <i class="fas fa-phone"></i>
                        <?= htmlspecialchars($co['phone']) ?>
                    </span>
                    <?php endif; ?>
                </div>

                <form method="post" style="margin-top:14px;">
                    <input type="hidden" name="company_id" value="<?= (int)$co['id'] ?>">
                    <button type="submit" style="
                        background: var(--primary);
                        color: #fff;
                        border-radius: 7px;
                        padding: 9px 18px;
                        font-size: 13px;
                        font-weight: 600;
                        font-family: inherit;
                        display: flex;
                        align-items: center;
                        gap: 7px;
                        transition: background 0.15s;
                    " onmouseover="this.style.background='#1d4ed8'" onmouseout="this.style.background='var(--primary)'">
                        <i class="fas fa-arrow-right-to-bracket"></i>
                        Enter Company
                    </button>
                </form>
            </div>
        </div>
        <?php endforeach; ?>
    </div>

    <div class="company-select-footer">
        <a href="<?= BASE_URL ?>/logout.php">
            <i class="fas fa-sign-out-alt"></i>
            Sign out
        </a>
    </div>

</div>

</body>
</html>
