<?php
session_start();
require_once __DIR__ . '/../../config/db.php';

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

$admin_username = $_SESSION['username'];
$admin_role = $_SESSION['role'];

$project_id = $_GET['id'] ?? null;
if (!$project_id) {
    die("Project not specified.");
}

// Fetch project details
$stmt = $pdo->prepare("SELECT * FROM projects WHERE id = ?");
$stmt->execute([$project_id]);
$project = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$project) die("Project not found.");

// Handle form submission
$success = '';
$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $user_id = $_POST['user_id'] ?? null;
    $role = $_POST['role'] ?? null;

    if ($user_id && $role) {
        $check = $pdo->prepare("SELECT * FROM project_memberships WHERE project_id = ? AND user_id = ?");
        $check->execute([$project_id, $user_id]);

        if ($check->rowCount() === 0) {
            $insert = $pdo->prepare("INSERT INTO project_memberships (project_id, user_id, role) VALUES (?, ?, ?)");
            $insert->execute([$project_id, $user_id, $role]);
            $success = "✅ User assigned successfully!";
        } else {
            $error = "❌ This user is already assigned to the project.";
        }
    } else {
        $error = "❌ Please select a user and role.";
    }
}

// Fetch all users
$users = $pdo->query("SELECT id, username, role FROM users ORDER BY username ASC")->fetchAll(PDO::FETCH_ASSOC);

// Fetch current project members
$membersStmt = $pdo->prepare("
    SELECT pm.id, u.username, pm.role 
    FROM project_memberships pm
    JOIN users u ON u.id = pm.user_id
    WHERE pm.project_id = ?
");
$membersStmt->execute([$project_id]);
$members = $membersStmt->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>Assign Member - Custora CRM</title>
<link rel="icon" href="../assets/img/custora_logo.png" type="image/png">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<style>
:root{--bg:#f4f7fa;--card-bg:rgba(173,216,230,0.35);--accent:#005f8d;--muted:#555;--text:#1b2430;--white:#fff;}
*{box-sizing:border-box;margin:0;padding:0;}
body{font-family:Inter,"Segoe UI",Roboto,Arial,sans-serif;background:var(--bg);color:var(--text);}
a{text-decoration:none;color:inherit;}
.app{display:flex;min-height:100vh;}
.sidebar{width:250px;background:skyblue;color:#003547;position:fixed;left:0;top:0;height:100vh;overflow:auto;z-index:200;transition:transform .3s ease-in-out;}
.sidebar .logo{text-align:center;margin:15px 0;}
.sidebar .logo img{width:180px;height:auto;margin-top:20px;}
.nav{margin-top:12px;padding-left:10px;}
.nav a{display:block;padding:10px 14px;color:#003547;border-radius:8px;margin-bottom:6px;font-weight:600;}
.nav a:hover{background:rgba(255,255,255,0.8);box-shadow:0 2px 6px rgba(0,0,0,0.06);}
.footer-note{text-align:center;font-size:13px;padding:10px;color:var(--muted);}
.main{margin-left:260px;padding:20px;width:100%;transition:margin-left .25s;}
.header{background:var(--accent);color:white;padding:15px 20px;border-radius:8px;display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;}
.header-left{display:flex;align-items:center;gap:10px;}
.hamburger{display:none;background:var(--accent);color:white;padding:8px 10px;border-radius:8px;cursor:pointer;font-size:20px;}
.overlay{display:none;position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.4);z-index:150;}
.content{background:var(--card-bg);padding:25px;border-radius:12px;box-shadow:0 4px 10px rgba(0,0,0,0.08);}
.content h3{color:var(--accent);margin-bottom:15px;}
.message{background:#d4edda;color:#155724;padding:10px 14px;border-radius:6px;margin-bottom:15px;}
.error-box{background:#f8d7da;color:#721c24;padding:10px 14px;border-radius:6px;margin-bottom:15px;}
label{display:block;margin-bottom:6px;font-weight:600;color:var(--text);}
input,select{width:100%;padding:10px;margin-bottom:15px;border-radius:8px;border:1px solid #ccc;font-size:14px;}
button{padding:12px 25px;background:var(--accent);color:white;border:none;border-radius:8px;cursor:pointer;font-weight:600;}
button:hover {background:#004466;}
.controls {display:flex;align-items:center;gap:10px;}
#darkToggle {padding:8px 10px;border:none;border-radius:8px;background:rgba(255,255,255,0.3);color:white;cursor:pointer;}
table{width:100%;border-collapse:collapse;margin-top:20px;}
th,td{padding:12px;border-bottom:1px solid #ddd;text-align:left;}
th{background:var(--accent);color:white;}
tr:hover{background:#f1f1f1;}
a.remove{color:red;text-decoration:none;}
@media(max-width:768px){.sidebar{transform:translateX(-280px);}.sidebar.active{transform:translateX(0);}.sidebar.active ~ .overlay{display:block;}.main{margin-left:0;padding:12px;}.hamburger{display:inline-block;}}
body.dark{--bg:#081014;--card-bg:rgba(255,255,255,0.05);--accent:#1fb6ff;--muted:#9aa6af;--text:#e6f2f6;--white:#0a0a0a;}
body.dark .sidebar{background:linear-gradient(180deg,#0b2b33,#072024);color:#bfeafc;}
body.dark .nav a{color:#bfeafc;}
body.dark .content h3{color:#1fb6ff;}
</style>
</head>
    <body>
        <div class="app">
            <aside class="sidebar" id="sidebar">
                <div class="logo"><img src="../assets/img/custora_logo.png" alt="Custora CRM"></div>
                <nav class="nav">
                    <a href="../"><i class="fas fa-gauge"></i> Dashboard</a>
                    <a href="../projects/"><i class="fas fa-diagram-project"></i> Manage Projects</a>
                    <a href="../users/"><i class="fas fa-users-cog"></i> Manage Users</a>
                    <a href="../issues/"><i class="fas fa-circle-exclamation"></i> All Issues</a>
                    <a href="../profile/"><i class="fas fa-user"></i> My Profile</a>
                    <a href="../../auth/logout.php" style="color:#b31b1b;"><i class="fas fa-sign-out-alt"></i> Logout</a>
                </nav>
                <div class="footer-note">&copy; <?= date('Y') ?> Digital Vortex Technologies</div>
            </aside>
        
            <div class="overlay" id="overlay" onclick="toggleSidebar()"></div>
        
            <main class="main">
                <div class="header">
                    <div class="header-left">
                        <div class="hamburger" id="hamburger" onclick="toggleSidebar()"><i class="fas fa-bars"></i></div>
                        <span>Welcome, <strong><?= htmlspecialchars($admin_username) ?></strong> (<?= htmlspecialchars($admin_role) ?>)</span>
                    </div>
                    <div class="controls">
        				<button id="darkToggle"><span id="darkLabel">Dark</span></button>
        				<a href="../../auth/logout.php" style="color:white;text-decoration:none;"><i class="fas fa-sign-out-alt"></i> Logout</a>
        			</div>
                </div>
        
                <div class="content" style="margin-top:20px;">
                    <h3><i class="fas fa-user-plus"></i> Assign Member to <u><?= htmlspecialchars($project['name']) ?></u></h3>
        
                    <?php if ($success): ?><div class="message"><?= $success ?></div><?php endif; ?>
                    <?php if ($error): ?><div class="error-box"><?= $error ?></div><?php endif; ?>
        
                    <form method="POST">
                        <label>Select User:</label>
                        <select name="user_id" required>
                            <option value="">-- Choose User --</option>
                            <?php foreach ($users as $u): ?>
                                <option value="<?= $u['id'] ?>"><?= htmlspecialchars($u['username'] . " (" . $u['role'] . ")") ?></option>
                            <?php endforeach; ?>
                        </select>
        
                        <label>Assign Role:</label>
                        <select name="role" required>
                            <option value="">-- Choose Role --</option>
                            <option value="reporter">Reporter</option>
                            <option value="support">Support</option>
                        </select>
        
                        <button type="submit"><i class="fas fa-user-plus"></i> Assign Member</button>
                    </form>
        
                    <h3>Current Project Members</h3>
                    <table>
                        <thead>
                            <tr>
                                <th>Username</th>
                                <th>Role</th>
                                <th>Remove</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if ($members): ?>
                                <?php foreach ($members as $m): ?>
                                    <tr>
                                        <td><?= htmlspecialchars($m['username']) ?></td>
                                        <td><?= htmlspecialchars($m['role']) ?></td>
                                        <td><a href="remove_member.php?id=<?= $m['id'] ?>&project_id=<?= $project_id ?>" class="remove" onclick="return confirm('Remove this member?');">Remove</a></td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr><td colspan="3">No members assigned yet.</td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </main>
        </div>
    
        <script>
            function toggleSidebar(){
                const sidebar=document.getElementById('sidebar');
                const overlay=document.getElementById('overlay');
                sidebar.classList.toggle('active');
                overlay.style.display=sidebar.classList.contains('active')?'block':'none';
            }
            (function(){
                const body=document.body,toggle=document.getElementById('darkToggle'),label=document.getElementById('darkLabel');
                if(localStorage.getItem('custora_dark')==='1'){body.classList.add('dark');}
            })();
            
            (function(){
                const body=document.body,toggle=document.getElementById('darkToggle'),label=document.getElementById('darkLabel');
                if(localStorage.getItem('custora_dark')==='1'){body.classList.add('dark');label.textContent='Light';}
                toggle.addEventListener('click',()=>{
                    body.classList.toggle('dark');
                    localStorage.setItem('custora_dark',body.classList.contains('dark')?'1':'0');
                    label.textContent=body.classList.contains('dark')?'Light':'Dark';
                });
            })();
        </script>
    </body>
</html>