<?php
require_once __DIR__ . '/includes/admin_auth.php';
requirePermission('manage_users');

require_once __DIR__ . '/includes/db.php'; // Ensure $db is your mysqli connection

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    $_SESSION['error'] = "Invalid request method";
    header("Location: users.php");
    exit();
}

// Get form data
$id = isset($_POST['id']) ? intval($_POST['id']) : null;
$username = trim($_POST['username']);
$email = trim($_POST['email']);
$fullName = trim($_POST['full_name']);
$roleId = intval($_POST['role_id']);
$isActive = intval($_POST['is_active']);
$password = trim($_POST['password'] ?? '');
$confirmPassword = trim($_POST['confirm_password'] ?? '');

// Validate data
if (empty($username) || empty($email) || empty($fullName)) {
    $_SESSION['error'] = "All fields are required";
    header("Location: users.php");
    exit();
}

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $_SESSION['error'] = "Invalid email format";
    header("Location: users.php");
    exit();
}

// Check if username or email already exists (for new users)
if (!$id) {
    if (empty($password) || $password !== $confirmPassword) {
        $_SESSION['error'] = "Passwords do not match or are empty";
        header("Location: users.php");
        exit();
    }

    $stmt = $db->prepare("SELECT id FROM admin_users WHERE username = ? OR email = ?");
    $stmt->bind_param("ss", $username, $email);
    $stmt->execute();
    $stmt->store_result();

    if ($stmt->num_rows > 0) {
        $_SESSION['error'] = "Username or email already exists";
        header("Location: users.php");
        exit();
    }
    $stmt->close();
}

try {
    if ($id) {
        // Update existing user
        if (!empty($password)) {
            $passwordHash = password_hash($password, PASSWORD_DEFAULT);
            $stmt = $db->prepare("
                UPDATE admin_users 
                SET email = ?, full_name = ?, role_id = ?, is_active = ?, password_hash = ?
                WHERE id = ?
            ");
            $stmt->bind_param("ssiiii", $email, $fullName, $roleId, $isActive, $passwordHash, $id);
        } else {
            $stmt = $db->prepare("
                UPDATE admin_users 
                SET email = ?, full_name = ?, role_id = ?, is_active = ?
                WHERE id = ?
            ");
            $stmt->bind_param("ssiii", $email, $fullName, $roleId, $isActive, $id);
        }

        if ($stmt->execute()) {
            $_SESSION['success'] = "User updated successfully";
        } else {
            throw new Exception("Execution failed: " . $stmt->error);
        }
        $stmt->close();

    } else {
        // Create new user
        $passwordHash = password_hash($password, PASSWORD_DEFAULT);
        $stmt = $db->prepare("
            INSERT INTO admin_users (username, email, full_name, role_id, is_active, password_hash)
            VALUES (?, ?, ?, ?, ?, ?)
        ");
        $stmt->bind_param("sssiss", $username, $email, $fullName, $roleId, $isActive, $passwordHash);

        if ($stmt->execute()) {
            $_SESSION['success'] = "User created successfully";
        } else {
            throw new Exception("Execution failed: " . $stmt->error);
        }
        $stmt->close();
    }

    header("Location: users.php");
    exit();

} catch (Exception $e) {
    $_SESSION['error'] = "Database error: " . $e->getMessage();
    header("Location: users.php");
    exit();
}
?>
