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

/* =========================
   AUTHORIZATION
========================= */
if (
    !isset($_SESSION['loggedin']) ||
    $_SESSION['loggedin'] !== true ||
    !isset($_SESSION['role']) ||
    $_SESSION['role'] !== 'admin'
) {
    die("
        <script>
            alert('Access denied. Only administrators can update users.');
            window.location.href = '../dashboard.php';
        </script>
    ");
}

/* =========================
   COMPANY CONTEXT
========================= */
if (!isset($_SESSION['company_id'])) {
    die("
        <script>
            alert('Company context missing. Please re-login.');
            window.location.href = '../sign-in.php';
        </script>
    ");
}

$company_id = (int) $_SESSION['company_id'];


/* =========================
   REQUEST VALIDATION
========================= */
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    die("Invalid request");
}

$id       = (int) ($_POST['id'] ?? 0);
$name     = trim($_POST['name'] ?? '');
$email    = trim($_POST['email'] ?? '');
$password = $_POST['password'] ?? '';
$confirm  = $_POST['confirm_password'] ?? '';
$role     = trim($_POST['role'] ?? '');

if ($id <= 0 || $name === '' || $email === '' || $role === '') {
    die("
        <script>
            alert('Missing required fields.');
            history.back();
        </script>
    ");
}

/* =========================
   VERIFY USER BELONGS TO COMPANY
========================= */
$check = $conn->prepare("
    SELECT id 
    FROM users 
    WHERE id = ? AND company_id = ?
    LIMIT 1
");
$check->bind_param("ii", $id, $company_id);
$check->execute();
$check->store_result();

if ($check->num_rows === 0) {
    die("
        <script>
            alert('User not found or access denied.');
            window.location.href = '../Admin/user-list.php';
        </script>
    ");
}

/* =========================
   UPDATE USER
========================= */
if (!empty($password)) {

    if ($password !== $confirm) {
        die("
            <script>
                alert('Passwords do not match.');
                history.back();
            </script>
        ");
    }

    $hashedPassword = password_hash($password, PASSWORD_DEFAULT);

    $stmt = $conn->prepare("
        UPDATE users 
        SET name = ?, email = ?, password = ?, role = ?
        WHERE id = ? AND company_id = ?
    ");
    $stmt->bind_param(
        "ssssii",
        $name,
        $email,
        $hashedPassword,
        $role,
        $id,
        $company_id
    );

} else {

    // Password unchanged
    $stmt = $conn->prepare("
        UPDATE users 
        SET name = ?, email = ?, role = ?
        WHERE id = ? AND company_id = ?
    ");
    $stmt->bind_param(
        "sssii",
        $name,
        $email,
        $role,
        $id,
        $company_id
    );
}

/* =========================
   EXECUTE
========================= */
if ($stmt->execute()) {
    echo "
        <script>
            alert('User updated successfully.');
            window.location.href = '../Admin/user-list.php';
        </script>
    ";
} else {
    echo "
        <script>
            alert('Update failed. Please contact system administrator.');
            window.location.href = '../Admin/user-list.php';
        </script>
    ";
}

$stmt->close();
$conn->close();
