<?php

date_default_timezone_set('Asia/Colombo');

require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../includes/csrf.php';
require_once __DIR__ . '/../includes/activity_log.php';

/*
|--------------------------------------------------------------------------
| Admin Only
|--------------------------------------------------------------------------
*/

if($_SESSION['role'] != 'admin')
{
    die("Access Denied");
}

/*
|--------------------------------------------------------------------------
| POST Only
|--------------------------------------------------------------------------
*/

if($_SERVER['REQUEST_METHOD'] != 'POST')
{
    die("Invalid Request");
}

/*
|--------------------------------------------------------------------------
| CSRF Validation
|--------------------------------------------------------------------------
*/

if(
    !isset($_POST['csrf_token']) ||
    !hash_equals(
        $_SESSION['csrf_token'],
        $_POST['csrf_token']
    )
)
{
    die("CSRF Validation Failed");
}

/*
|--------------------------------------------------------------------------
| Collect Data
|--------------------------------------------------------------------------
*/

$id = (int)$_POST['id'];

if ($id <= 0) die('Invalid user ID.');

// Protect System Administrator
if ($id == 1 && $_SESSION['user_id'] != 1) {
    die("Access Denied");
}

$fullname   = trim($_POST['fullname']);
$email      = trim($_POST['email']);
$phone      = trim($_POST['phone']);
$workplace  = trim($_POST['workplace']);
$zone_name  = trim($_POST['zone_name']);
$role       = trim($_POST['role']);
$status     = trim($_POST['status']);

$password         = $_POST['password'] ?? '';
$confirm_password = $_POST['confirm_password'] ?? '';

/*
|--------------------------------------------------------------------------
| Validation
|--------------------------------------------------------------------------
*/

if(empty($fullname))
{
    die("Full Name Required");
}

if (!filter_var($email, FILTER_VALIDATE_EMAIL) || !in_array($role, ['admin', 'zonal_director', 'user'], true) || !in_array($status, ['Active', 'Inactive'], true))
{
    die('Invalid user data.');
}

if ($role === 'zonal_director' && $zone_name === '') die('Zone is required for zonal directors.');

if (!empty($password) && strlen($password) < 8) die('Password must be at least 8 characters.');

if(empty($phone))
{
    die("Phone Number Required");
}

if(
    !empty($password)
    &&
    $password != $confirm_password
)
{
    die("Passwords do not match");
}

/*
|--------------------------------------------------------------------------
| Update User
|--------------------------------------------------------------------------
*/

if($role != 'zonal_director')
{
    $zone_name = NULL;
}

$duplicate = mysqli_prepare($conn, 'SELECT id FROM users WHERE email=? AND id<>?');
mysqli_stmt_bind_param($duplicate, 'si', $email, $id);
mysqli_stmt_execute($duplicate);
if (mysqli_num_rows(mysqli_stmt_get_result($duplicate)) > 0) die('Email already exists.');
mysqli_stmt_close($duplicate);

if(empty($password))
{

    $stmt = mysqli_prepare(

        $conn,

        "UPDATE users

        SET

        fullname=?,
        email=?,
        phone=?,
        workplace=?,
        zone_name=?,
        role=?,
        status=?

        WHERE id=?"

    );

    mysqli_stmt_bind_param(

        $stmt,

        "sssssssi",

        $fullname,
        $email,
        $phone,
        $workplace,
        $zone_name,
        $role,
        $status,
        $id

    );

}
else
{

    $password =
    password_hash(
        $password,
        PASSWORD_DEFAULT
    );

    $stmt = mysqli_prepare(

        $conn,

        "UPDATE users

        SET

        fullname=?,
        email=?,
        phone=?,
        workplace=?,
        zone_name=?,
        password=?,
        role=?,
        status=?

        WHERE id=?"

    );

    mysqli_stmt_bind_param(

        $stmt,

        "ssssssssi",

        $fullname,
        $email,
        $phone,
        $workplace,
        $zone_name,
        $password,
        $role,
        $status,
        $id

    );

}

/*
|--------------------------------------------------------------------------
| Execute
|--------------------------------------------------------------------------
*/

if(mysqli_stmt_execute($stmt))
{
    logActivity(
        $conn,
        'User Management',
        'Update User',
        'Updated user "' .
        $fullname .
        '" (' .
        $role .
        ')'
    );

    $_SESSION['success'] =
    "User Updated Successfully.";

}
else
{

    $_SESSION['error'] =
    "Failed to Update User.";

}

header("Location: users.php");

exit();
