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

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

    $id = trim($_POST['id']);
    $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 = $_POST['password'];

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

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

    $updateProfileImage = '';
    $updateParams = [];

    // Handle profile image upload
    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;
            if (move_uploaded_file($_FILES['profile_image']['tmp_name'], $uploadDir . $imageName)) {
                $updateProfileImage = ", profile_image = ?";
                $updateParams[] = $imageName;
            }
        }
    }

    try {
        if (!empty($password)) {
            $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
            $updatePassword = ", password = ?";
            $updateParams[] = $hashedPassword;
        } else {
            $updatePassword = "";
        }

        $sql = "UPDATE users SET username = ?, email = ?, contact = ?, site_id = ?, employment_status = ?, status = ?, role = ? $updateProfileImage $updatePassword WHERE id = ?";
        $stmt = $pdo->prepare($sql);

        $updateParams = array_merge([$username, $email, $contact, $site_id, $employment_status, $status, $role], $updateParams, [$id]);
        $stmt->execute($updateParams);

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

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