<?php
session_start();
require_once __DIR__ . '/../includes/database.php';

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

$action = $_POST['action'] ?? '';

switch ($action) {
    case 'add':
        addUser();
        break;
    case 'edit':
        editUser();
        break;
    case 'toggle_status':
        toggleUserStatus();
        break;
    case 'delete':
        deleteUser();
        break;
    default:
        $_SESSION['message'] = 'Invalid action!';
        $_SESSION['message_type'] = 'danger';
        header("Location: users.php");
        exit();
}

function addUser() {
    global $pdo;
    
    $full_name = trim($_POST['full_name']);
    $username = trim($_POST['username']);
    $email = trim($_POST['email']);
    $password = $_POST['password'];
    $role = $_POST['role'];
    $status = $_POST['status'] ?? 1;
    
    // Validation
    if (empty($full_name) || empty($username) || empty($password) || empty($role)) {
        $_SESSION['message'] = 'All required fields must be filled!';
        $_SESSION['message_type'] = 'danger';
        header("Location: users.php");
        exit();
    }
    
    if (strlen($password) < 6) {
        $_SESSION['message'] = 'Password must be at least 6 characters!';
        $_SESSION['message_type'] = 'danger';
        header("Location: users.php");
        exit();
    }
    
    // Check if username already exists
    $checkQuery = "SELECT COUNT(*) FROM users WHERE username = ?";
    $stmt = $pdo->prepare($checkQuery);
    $stmt->execute([$username]);
    
    if ($stmt->fetchColumn() > 0) {
        $_SESSION['message'] = 'Username already exists!';
        $_SESSION['message_type'] = 'danger';
        header("Location: users.php");
        exit();
    }
    
    // Hash password
    $hashed_password = password_hash($password, PASSWORD_DEFAULT);
    
    // Insert user
    $query = "INSERT INTO users (full_name, username, email, password, role, status) 
              VALUES (?, ?, ?, ?, ?, ?)";
    
    try {
        $stmt = $pdo->prepare($query);
        $stmt->execute([$full_name, $username, $email, $hashed_password, $role, $status]);
        
        $_SESSION['message'] = 'User added successfully!';
        $_SESSION['message_type'] = 'success';
        header("Location: users.php");
        exit();
    } catch (PDOException $e) {
        $_SESSION['message'] = 'Error adding user: ' . $e->getMessage();
        $_SESSION['message_type'] = 'danger';
        header("Location: users.php");
        exit();
    }
}

function editUser() {
    global $pdo;
    
    $user_id = $_POST['user_id'];
    $full_name = trim($_POST['full_name']);
    $username = trim($_POST['username']);
    $email = trim($_POST['email']);
    $password = $_POST['password'];
    $role = $_POST['role'];
    $status = $_POST['status'] ?? 1;
    
    // Validation
    if (empty($full_name) || empty($username) || empty($role)) {
        $_SESSION['message'] = 'All required fields must be filled!';
        $_SESSION['message_type'] = 'danger';
        header("Location: users.php");
        exit();
    }
    
    // Check if username already exists (excluding current user)
    $checkQuery = "SELECT COUNT(*) FROM users WHERE username = ? AND id != ?";
    $stmt = $pdo->prepare($checkQuery);
    $stmt->execute([$username, $user_id]);
    
    if ($stmt->fetchColumn() > 0) {
        $_SESSION['message'] = 'Username already exists!';
        $_SESSION['message_type'] = 'danger';
        header("Location: users.php");
        exit();
    }
    
    // Update query
    if (!empty($password)) {
        if (strlen($password) < 6) {
            $_SESSION['message'] = 'Password must be at least 6 characters!';
            $_SESSION['message_type'] = 'danger';
            header("Location: users.php");
            exit();
        }
        
        $hashed_password = password_hash($password, PASSWORD_DEFAULT);
        $query = "UPDATE users SET full_name = ?, username = ?, email = ?, password = ?, role = ?, status = ? WHERE id = ?";
        $params = [$full_name, $username, $email, $hashed_password, $role, $status, $user_id];
    } else {
        $query = "UPDATE users SET full_name = ?, username = ?, email = ?, role = ?, status = ? WHERE id = ?";
        $params = [$full_name, $username, $email, $role, $status, $user_id];
    }
    
    try {
        $stmt = $pdo->prepare($query);
        $stmt->execute($params);
        
        $_SESSION['message'] = 'User updated successfully!';
        $_SESSION['message_type'] = 'success';
        header("Location: users.php");
        exit();
    } catch (PDOException $e) {
        $_SESSION['message'] = 'Error updating user: ' . $e->getMessage();
        $_SESSION['message_type'] = 'danger';
        header("Location: users.php");
        exit();
    }
}

function toggleUserStatus() {
    global $pdo;
    
    $user_id = $_POST['user_id'];
    
    // Get current status
    $query = "SELECT status FROM users WHERE id = ?";
    $stmt = $pdo->prepare($query);
    $stmt->execute([$user_id]);
    $current = $stmt->fetchColumn();
    
    $new_status = $current ? 0 : 1;
    
    // Update status
    $updateQuery = "UPDATE users SET status = ? WHERE id = ?";
    $stmt = $pdo->prepare($updateQuery);
    $stmt->execute([$new_status, $user_id]);
    
    echo json_encode(['success' => true, 'message' => 'Status updated successfully']);
}

function deleteUser() {
    global $pdo;
    
    $user_id = $_POST['user_id'];
    
    // Prevent deleting yourself
    if ($user_id == $_SESSION['user_id']) {
        echo json_encode(['success' => false, 'message' => 'You cannot delete your own account!']);
        exit();
    }
    
    try {
        $query = "DELETE FROM users WHERE id = ?";
        $stmt = $pdo->prepare($query);
        $stmt->execute([$user_id]);
        
        echo json_encode(['success' => true, 'message' => 'User deleted successfully']);
    } catch (PDOException $e) {
        echo json_encode(['success' => false, 'message' => 'Error deleting user: ' . $e->getMessage()]);
    }
}
?>