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

$company_id = (int)($_GET['company_id'] ?? $_POST['company_id'] ?? 0);
$user_id = (int)($_GET['user_id'] ?? $_POST['user_id'] ?? 0);

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

$error = '';

$stmt = $db->prepare("
    SELECT cu.company_id,
           cu.user_id,
           cu.company_role,
           c.company_name,
           u.full_name,
           u.email
    FROM company_users cu
    INNER JOIN companies c ON cu.company_id = c.id
    INNER JOIN users u ON cu.user_id = u.id
    WHERE cu.company_id = :company_id
      AND cu.user_id = :user_id
    LIMIT 1
");
$stmt->bindValue(':company_id', $company_id, PDO::PARAM_INT);
$stmt->bindValue(':user_id', $user_id, PDO::PARAM_INT);
$stmt->execute();
$member = $stmt->fetch(PDO::FETCH_ASSOC);

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

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

    if (!in_array($company_role, ['member', 'admin', 'owner'], true)) {
        $error = "Invalid company role.";
    } else {
        $update = $db->prepare("
            UPDATE company_users
            SET company_role = :company_role
            WHERE company_id = :company_id
              AND user_id = :user_id
        ");
        $update->bindValue(':company_role', $company_role, PDO::PARAM_STR);
        $update->bindValue(':company_id', $company_id, PDO::PARAM_INT);
        $update->bindValue(':user_id', $user_id, PDO::PARAM_INT);
        $update->execute();

        header("Location: /dms/add_user_to_company.php?company_id=" . $company_id . "&updated=1");
        exit;
    }

    $member['company_role'] = $company_role;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit Company User Role</title>
    <link rel="stylesheet" href="/dms/assets/css/app.css">
</head>
<body>
<div class="layout">
    <?php include 'nav.php'; ?>

    <main class="main">
        <div class="hero">
            <div class="hero-top">
                <div>
                    <h1>Edit Company User</h1>
                    <p>Update member role in <?php echo htmlspecialchars($member['company_name']); ?>.</p>
                </div>
                <div class="welcome-badge">
                    <?php echo htmlspecialchars($_SESSION['full_name'] ?? 'User'); ?>
                </div>
            </div>
        </div>

        <div class="card">
            <?php if ($error !== ''): ?>
                <div class="card" style="background:#fff1f1;color:#b42318;margin-bottom:12px;">
                    <?php echo htmlspecialchars($error); ?>
                </div>
            <?php endif; ?>

            <form method="POST" class="form-grid">
                <input type="hidden" name="company_id" value="<?php echo (int)$member['company_id']; ?>">
                <input type="hidden" name="user_id" value="<?php echo (int)$member['user_id']; ?>">

                <div class="form-group">
                    <label>Full Name</label>
                    <input type="text" value="<?php echo htmlspecialchars($member['full_name']); ?>" readonly>
                </div>

                <div class="form-group">
                    <label>Email</label>
                    <input type="text" value="<?php echo htmlspecialchars($member['email']); ?>" readonly>
                </div>

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

                <div style="display:flex; gap:10px; flex-wrap:wrap; margin-top:12px;">
                    <button type="submit" class="btn btn-primary">Save Changes</button>
                    <a href="/dms/add_user_to_company.php?company_id=<?php echo (int)$member['company_id']; ?>" class="btn btn-secondary">Cancel</a>
                </div>
            </form>
        </div>
    </main>
</div>
</body>
</html>