<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

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

$company_id = 0;

if (isset($_GET['company_id'])) {
    $company_id = (int)$_GET['company_id'];
} elseif (isset($_GET['id'])) {
    $company_id = (int)$_GET['id'];
} elseif (isset($_POST['company_id'])) {
    $company_id = (int)$_POST['company_id'];
}

if ($company_id <= 0) {
    die("Invalid company ID.");
}

$stmtCompany = $db->prepare("
    SELECT *
    FROM companies
    WHERE id = :id
    LIMIT 1
");
$stmtCompany->bindValue(':id', $company_id, PDO::PARAM_INT);
$stmtCompany->execute();
$company = $stmtCompany->fetch(PDO::FETCH_ASSOC);

if (!$company) {
    die("Company not found.");
}

$success = '';
$errors = [];

if (isset($_GET['updated']) && $_GET['updated'] == 1) {
    $success = "Company user role updated successfully.";
}

if (isset($_GET['deleted']) && $_GET['deleted'] == 1) {
    $success = "User removed from company successfully.";
}

$form = [
    'user_id' => '',
    'company_role' => 'member'
];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $form['user_id'] = (string)($_POST['user_id'] ?? '');
    $form['company_role'] = trim($_POST['company_role'] ?? 'member');

    $user_id = (int)$form['user_id'];
    $company_role = $form['company_role'];

    if ($user_id <= 0) {
        $errors[] = "Please select a user.";
    }

    if (!in_array($company_role, ['member', 'admin', 'owner'], true)) {
        $errors[] = "Invalid company role.";
    }

    if (empty($errors)) {
        try {
            $stmtCheckUser = $db->prepare("
                SELECT id, full_name, email
                FROM users
                WHERE id = :user_id
                LIMIT 1
            ");
            $stmtCheckUser->bindValue(':user_id', $user_id, PDO::PARAM_INT);
            $stmtCheckUser->execute();
            $selectedUser = $stmtCheckUser->fetch(PDO::FETCH_ASSOC);

            if (!$selectedUser) {
                $errors[] = "Selected user not found.";
            } else {
                $stmtCheckMembership = $db->prepare("
                    SELECT id
                    FROM company_users
                    WHERE company_id = :company_id
                      AND user_id = :user_id
                    LIMIT 1
                ");
                $stmtCheckMembership->bindValue(':company_id', $company_id, PDO::PARAM_INT);
                $stmtCheckMembership->bindValue(':user_id', $user_id, PDO::PARAM_INT);
                $stmtCheckMembership->execute();
                $existingMembership = $stmtCheckMembership->fetch(PDO::FETCH_ASSOC);

                if ($existingMembership) {
                    $errors[] = "This user is already in this company.";
                } else {
                    $stmtInsert = $db->prepare("
                        INSERT INTO company_users (company_id, user_id, company_role)
                        VALUES (:company_id, :user_id, :company_role)
                    ");
                    $stmtInsert->bindValue(':company_id', $company_id, PDO::PARAM_INT);
                    $stmtInsert->bindValue(':user_id', $user_id, PDO::PARAM_INT);
                    $stmtInsert->bindValue(':company_role', $company_role, PDO::PARAM_STR);
                    $stmtInsert->execute();

                    $success = "User added to company successfully.";

                    $form = [
                        'user_id' => '',
                        'company_role' => 'member'
                    ];
                }
            }
        } catch (PDOException $e) {
            $errors[] = "Database error: " . $e->getMessage();
        } catch (Throwable $e) {
            $errors[] = "Unexpected error: " . $e->getMessage();
        }
    }
}

$stmtUsers = $db->prepare("
    SELECT id, full_name, email, role
    FROM users
    WHERE role != 'guest'
    ORDER BY full_name ASC
");
$stmtUsers->execute();
$users = $stmtUsers->fetchAll(PDO::FETCH_ASSOC);

$stmtMembers = $db->prepare("
    SELECT cu.id AS company_user_id,
           cu.company_id,
           cu.user_id,
           cu.company_role,
           u.full_name,
           u.email
    FROM company_users cu
    INNER JOIN users u ON cu.user_id = u.id
    WHERE cu.company_id = :company_id
    ORDER BY u.full_name ASC
");
$stmtMembers->bindValue(':company_id', $company_id, PDO::PARAM_INT);
$stmtMembers->execute();
$members = $stmtMembers->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Company Users</title>
    <link rel="stylesheet" href="/dms/assets/css/app.css">
    <style>
        .alert-box {
            padding: 14px 16px;
            border-radius: 14px;
            margin-bottom: 18px;
            font-weight: 600;
        }

        .alert-success {
            background: #ecfdf3;
            color: #027a48;
        }

        .alert-danger {
            background: #fef3f2;
            color: #b42318;
        }

        .workspace-badge {
            display: inline-flex;
            align-items: center;
            padding: 8px 12px;
            border-radius: 999px;
            font-size: 13px;
            font-weight: 700;
            background: #eff8ff;
            color: #175cd3;
            border: 1px solid #b2ddff;
            margin-top: 12px;
        }

        .action-group {
            display: flex;
            gap: 8px;
            flex-wrap: wrap;
        }
    </style>
</head>
<body>
<div class="layout">
    <?php include 'nav.php'; ?>

    <main class="main">
        <div class="hero">
            <div class="hero-top">
                <div>
                    <h1>Manage Company Users</h1>
                    <p>
                        Add, edit, and remove users for
                        <?php echo htmlspecialchars($company['company_name'] ?? 'Company'); ?>.
                    </p>
                    <div class="workspace-badge">Admin Page</div>
                </div>
                <div class="welcome-badge">
                    <?php echo htmlspecialchars($_SESSION['full_name'] ?? 'User'); ?>
                </div>
            </div>
        </div>

        <?php if (!empty($errors)): ?>
            <div class="alert-box alert-danger">
                <?php foreach ($errors as $error): ?>
                    <div><?php echo htmlspecialchars($error); ?></div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>

        <?php if ($success !== ''): ?>
            <div class="alert-box alert-success">
                <?php echo htmlspecialchars($success); ?>
            </div>
        <?php endif; ?>

        <div class="card">
            <div class="section-title">Assign User</div>
            <div class="section-subtext">Select an existing user and assign company access.</div>

            <form method="POST" style="display:grid; gap:16px; margin-top:18px;">
                <input type="hidden" name="company_id" value="<?php echo (int)$company_id; ?>">

                <div>
                    <label for="user_id">User</label>
                    <select name="user_id" id="user_id" class="search-input" required>
                        <option value="">-- Select User --</option>
                        <?php foreach ($users as $user): ?>
                            <option value="<?php echo (int)$user['id']; ?>"
                                <?php echo ((string)$user['id'] === $form['user_id']) ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($user['full_name'] . ' - ' . $user['email']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div>
                    <label for="company_role">Company Role</label>
                    <select name="company_role" id="company_role" class="search-input" required>
                        <option value="member" <?php echo $form['company_role'] === 'member' ? 'selected' : ''; ?>>Member</option>
                        <option value="admin" <?php echo $form['company_role'] === 'admin' ? 'selected' : ''; ?>>Admin</option>
                        <option value="owner" <?php echo $form['company_role'] === 'owner' ? 'selected' : ''; ?>>Owner</option>
                    </select>
                </div>

                <div style="display:flex; gap:10px; flex-wrap:wrap;">
                    <button type="submit" class="btn btn-primary">Add User</button>
                    <a href="/dms/companies.php" class="btn btn-secondary">Back</a>
                </div>
            </form>
        </div>

        <div class="card">
            <div class="section-title">Company Members</div>
            <div class="section-subtext">Current users in this company.</div>

            <div class="table-wrap" style="margin-top:16px;">
                <table class="admin-table">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Full Name</th>
                            <th>Email</th>
                            <th>Company Role</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php if (!empty($members)): ?>
                        <?php foreach ($members as $member): ?>
                            <tr>
                                <td>
                                    <span class="chip">#<?php echo (int)$member['user_id']; ?></span>
                                </td>
                                <td><?php echo htmlspecialchars($member['full_name'] ?? '-'); ?></td>
                                <td><?php echo htmlspecialchars($member['email'] ?? '-'); ?></td>
                                <td>
                                    <span class="badge info">
                                        <?php echo htmlspecialchars($member['company_role'] ?? 'member'); ?>
                                    </span>
                                </td>
                                <td>
                                    <div class="action-group">
                                        <a class="btn btn-primary btn-sm"
                                           href="/dms/edit_company_user.php?company_id=<?php echo (int)$member['company_id']; ?>&user_id=<?php echo (int)$member['user_id']; ?>">
                                           Edit Role
                                        </a>

                                        <a class="btn btn-danger btn-sm"
                                           href="/dms/delete_company_user.php?company_id=<?php echo (int)$member['company_id']; ?>&user_id=<?php echo (int)$member['user_id']; ?>"
                                           onclick="return confirm('Are you sure you want to remove this user from the company?');">
                                           Remove
                                        </a>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="5">
                                <div class="empty-state">No members in this company yet.</div>
                            </td>
                        </tr>
                    <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </main>
</div>
</body>
</html>