<?php
session_start();
if (!isset($_SESSION['logged_in'])) {
    header('Location: login.php');
    exit;
}

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/helpers.php';

/* Permission */
if (!can('users','add')) {
    die('Access Denied');
}

$message = '';

/* Roles (من 2 فما فوق فقط) */
$roles = $pdo->query("
    SELECT role_id, role_name
    FROM roles
    WHERE role_id >= 2
    ORDER BY role_id
")->fetchAll();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $username  = trim($_POST['username']);
    $full_name = trim($_POST['full_name']);
    $password  = $_POST['password'];
    $role_id   = (int)$_POST['role_id'];
    $status    = isset($_POST['status']) ? 'active' : 'inactive';

    /* حماية إضافية */
    if ($role_id < 2) {
        die('Invalid Role Selection');
    }

    if ($username === '' || $password === '' || $full_name === '') {
        $message = "<div class='alert danger'>All fields are required</div>";
    } else {

        /* Check username */
        $chk = $pdo->prepare("SELECT COUNT(*) FROM users WHERE username=?");
        $chk->execute([$username]);
        if ($chk->fetchColumn() > 0) {
            $message = "<div class='alert danger'>Username already exists</div>";
        } else {

            $hash = password_hash($password, PASSWORD_DEFAULT);

            $stmt = $pdo->prepare("
                INSERT INTO users
                (username, password, full_name, role_id, status)
                VALUES (?, ?, ?, ?, ?)
            ");
            $stmt->execute([
                $username,
                $hash,
                $full_name,
                $role_id,
                $status
            ]);

            /* ✅ التحويل إلى صفحة عرض المستخدمين */
            header('Location: users.php?added=1');
            exit;
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Add User</title>
<link rel="stylesheet" href="../assets/font-awesome/css/all.min.css">

<style>
body{margin:0;font-family:'Segoe UI',Arial;background:#f1f5f9}
.container{padding:30px}
.card{max-width:600px;margin:auto;background:#fff;border-radius:14px;border:1px solid #e5e7eb;padding:25px}

h2{margin-top:0}

.form-group{margin-bottom:15px}
label{font-size:13px;font-weight:700;color:#374151}
input,select{
    width:100%;padding:10px;border-radius:8px;
    border:1px solid #d1d5db;font-size:14px
}

/* Switch */
.switch{position:relative;display:inline-block;width:55px;height:28px}
.switch input{opacity:0;width:0;height:0}
.slider{
    position:absolute;cursor:pointer;top:0;left:0;right:0;bottom:0;
    background:#ccc;border-radius:34px;transition:.4s
}
.slider:before{
    position:absolute;content:"";height:20px;width:20px;
    left:4px;bottom:4px;background:white;border-radius:50%;transition:.4s
}
input:checked + .slider{background:#16a34a}
input:checked + .slider:before{transform:translateX(26px)}

.actions{margin-top:20px;display:flex;gap:10px}
.btn{padding:10px 18px;border-radius:8px;font-weight:700;text-decoration:none;border:none;cursor:pointer}
.btn-save{background:#16a34a;color:#fff}
.btn-back{background:#374151;color:#fff}

.alert{padding:12px;border-radius:8px;margin-bottom:15px;font-weight:700}
.success{background:#dcfce7;color:#166534}
.danger{background:#fee2e2;color:#991b1b}
</style>
</head>
<body>

<div class="container">
<div class="card">

<h2><i class="fas fa-user-plus"></i> Add New User</h2>

<?= $message ?>

<form method="post">

<div class="form-group">
    <label>Username</label>
    <input type="text" name="username" required>
</div>

<div class="form-group">
    <label>Full Name</label>
    <input type="text" name="full_name" required>
</div>

<div class="form-group">
    <label>Password</label>
    <input type="password" name="password" required>
</div>

<div class="form-group">
    <label>Role</label>
    <select name="role_id" required>
        <option value="">-- Select Role --</option>
        <?php foreach($roles as $r): ?>
            <option value="<?= $r['role_id'] ?>">
                <?= htmlspecialchars($r['role_name']) ?>
            </option>
        <?php endforeach; ?>
    </select>
</div>

<div class="form-group">
    <label>Status</label><br>
    <label class="switch">
        <input type="checkbox" name="status" checked>
        <span class="slider"></span>
    </label>
</div>

<div class="actions">
    <button class="btn btn-save"><i class="fas fa-save"></i> Save</button>
    <a href="users.php" class="btn btn-back">Cancel</a>
</div>

</form>

</div>
</div>

</body>
</html>
