<?php
// api/users.php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

header('Content-Type: application/json');
header('Access-Control-Allow-Origin', '*');

require_once __DIR__ . '/../../config.php';

$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? ($_POST['action'] ?? 'list');

try {
    // LIST USERS
    if ($method === 'GET' && $action === 'list') {
        $sql = "SELECT Id, FullName, Username, Email, Role, AllowWebAccess, LastModified
                FROM Users
                ORDER BY FullName ASC";
        $stmt = $pdo->query($sql);
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
        echo json_encode($rows);
        exit;
    }

    // CREATE / UPDATE USER
    if ($method === 'POST' && $action === 'save') {
        $id       = isset($_POST['id']) ? (int)$_POST['id'] : 0;
        $fullName = trim($_POST['fullName'] ?? '');
        $username = trim($_POST['username'] ?? '');
        $email    = trim($_POST['email'] ?? '');
        $role     = trim($_POST['role'] ?? '');
        $allowWeb = isset($_POST['allowWeb']) ? (int)$_POST['allowWeb'] : 0;
        $password = $_POST['password'] ?? '';

        if ($fullName === '' || $username === '' || $email === '' || $role === '') {
            http_response_code(400);
            echo json_encode([
                'success' => false,
                'message' => 'Full name, username, email and role are required.'
            ]);
            exit;
        }

        // basic check for existing username/email on insert or changing
        if ($id === 0) {
            $chk = $pdo->prepare("SELECT COUNT(*) FROM Users WHERE Username = :u OR Email = :e");
            $chk->execute([':u' => $username, ':e' => $email]);
            if ($chk->fetchColumn() > 0) {
                http_response_code(400);
                echo json_encode([
                    'success' => false,
                    'message' => 'Username or email already exists.'
                ]);
                exit;
            }
        } else {
            $chk = $pdo->prepare("SELECT COUNT(*) FROM Users WHERE (Username = :u OR Email = :e) AND Id <> :id");
            $chk->execute([':u' => $username, ':e' => $email, ':id' => $id]);
            if ($chk->fetchColumn() > 0) {
                http_response_code(400);
                echo json_encode([
                    'success' => false,
                    'message' => 'Username or email already exists.'
                ]);
                exit;
            }
        }

        $passwordHashSql = '';
        $params = [
            ':fullName' => $fullName,
            ':username' => $username,
            ':email'    => $email,
            ':role'     => $role,
            ':allow'    => $allowWeb
        ];

        if ($id === 0) {
            if ($password === '') {
                http_response_code(400);
                echo json_encode([
                    'success' => false,
                    'message' => 'Password is required for new users.'
                ]);
                exit;
            }

            $hash = password_hash($password, PASSWORD_DEFAULT);
            $sql = "INSERT INTO Users (FullName, Username, Email, Role, AllowWebAccess, PasswordHash)
                    VALUES (:fullName, :username, :email, :role, :allow, :pwd)";
            $params[':pwd'] = $hash;
            $stmt = $pdo->prepare($sql);
            $stmt->execute($params);
            $id = (int)$pdo->lastInsertId();
            // LastModified is set automatically by MySQL on insert
        } else {
            if ($password !== '') {
                $passwordHashSql = ", PasswordHash = :pwd";
                $params[':pwd'] = password_hash($password, PASSWORD_DEFAULT);
            }

            $sql = "UPDATE Users
                    SET FullName = :fullName,
                        Username = :username,
                        Email = :email,
                        Role = :role,
                        AllowWebAccess = :allow
                        $passwordHashSql
                    WHERE Id = :id";
            $params[':id'] = $id;
            $stmt = $pdo->prepare($sql);
            $stmt->execute($params);
            // LastModified auto-updates because of ON UPDATE CURRENT_TIMESTAMP
        }

        echo json_encode(['success' => true, 'id' => $id]);
        exit;
    }

    // RESET PASSWORD
    if ($method === 'POST' && $action === 'reset_password') {
        $id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
        $password = $_POST['password'] ?? '';

        if ($id <= 0 || $password === '') {
            http_response_code(400);
            echo json_encode([
                'success' => false,
                'message' => 'User id and new password are required.'
            ]);
            exit;
        }

        $hash = password_hash($password, PASSWORD_DEFAULT);
        $stmt = $pdo->prepare("UPDATE Users SET PasswordHash = :pwd WHERE Id = :id");
        $stmt->execute([':pwd' => $hash, ':id' => $id]);
        // LastModified auto-updates here as well

        echo json_encode(['success' => true]);
        exit;
    }

    // TOGGLE WEB ACCESS
    if ($method === 'POST' && $action === 'toggle_web') {
        $id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
        $allow = isset($_POST['allowWeb']) ? (int)$_POST['allowWeb'] : 0;

        if ($id <= 0) {
            http_response_code(400);
            echo json_encode([
                'success' => false,
                'message' => 'User id is required.'
            ]);
            exit;
        }

        $stmt = $pdo->prepare("UPDATE Users SET AllowWebAccess = :allow WHERE Id = :id");
        $stmt->execute([':allow' => $allow, ':id' => $id]);
        // LastModified auto-updates here as well

        echo json_encode(['success' => true]);
        exit;
    }

    // DELETE USER
    if ($method === 'POST' && $action === 'delete') {
        $id = isset($_POST['id']) ? (int)$_POST['id'] : 0;

        if ($id <= 0) {
            http_response_code(400);
            echo json_encode([
                'success' => false,
                'message' => 'Valid user id is required.'
            ]);
            exit;
        }

        $stmt = $pdo->prepare("DELETE FROM Users WHERE Id = :id");
        $stmt->execute([':id' => $id]);

        echo json_encode([
            'success' => true,
            'message' => 'User deleted successfully.'
        ]);
        exit;
    }

    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Invalid action.']);
} catch (Exception $ex) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Server error',
        'details' => $ex->getMessage()
    ]);
}
