<?php
session_start();
require_once '../includes/config.php';
require_once '../includes/functions.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verifyCSRFToken($_POST['csrf_token'], 'add_user')) {
        $_SESSION['toast'] = ['message' => 'Invalid CSRF token.', 'type' => 'danger'];
        header("Location: manage_users.php");
        exit;
    }

    $username = trim($_POST['username']);
    $email = trim($_POST['email']);
    $contact = trim($_POST['contact']);
    $site_id = trim($_POST['site_id']);
    $employment_status = trim($_POST['employment_status']); // Corrected field name
    $status = trim($_POST['status']);
    $role = trim($_POST['role']);
    $password_raw = $_POST['password'];

    if (empty($username) || empty($email) || empty($role) || empty($password_raw)) {
        $_SESSION['toast'] = ['message' => 'All fields are required.', 'type' => 'danger'];
        header("Location: manage_users.php");
        exit;
    }

    $password = password_hash($password_raw, PASSWORD_DEFAULT);

    $uploadDir = '../uploads/users/';
    if (!file_exists($uploadDir)) {
        mkdir($uploadDir, 0777, true);
    }

    $imageName = null;
    if (!empty($_FILES['profile_image']['name'])) {
        $ext = strtolower(pathinfo($_FILES['profile_image']['name'], PATHINFO_EXTENSION));
        $allowed = ['jpg', 'jpeg', 'png', 'gif'];
        if (in_array($ext, $allowed)) {
            $imageName = uniqid() . '.' . $ext;
            move_uploaded_file($_FILES['profile_image']['tmp_name'], $uploadDir . $imageName);
        }
    }

    try {
        $stmt = $pdo->prepare("INSERT INTO users (username, email, contact, site_id, employment_status, status, role, password, profile_image) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([$username, $email, $contact, $site_id, $employment_status, $status, $role, $password, $imageName]);

        $_SESSION['toast'] = ['message' => 'User added successfully.', 'type' => 'success'];
    } catch (Exception $e) {
        $_SESSION['toast'] = ['message' => 'Error: ' . $e->getMessage(), 'type' => 'danger'];
    }
}

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