<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");
header("Content-Type: application/json; charset=UTF-8");

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

require_once __DIR__ . '/../config/Database.php';
require_once __DIR__ . '/../models/User.php';

$method = $_SERVER['REQUEST_METHOD'];
$action = isset($_GET['action']) ? $_GET['action'] : '';

$user = new User();

if ($method === 'POST' && $action === 'login') {
    $data = json_decode(file_get_contents("php://input"), true);
    
    if (!isset($data['id']) || !isset($data['pin'])) {
        http_response_code(400);
        echo json_encode(['error' => 'Missing credentials']);
        exit;
    }
    
    $result = $user->authenticate($data['id'], $data['pin']);
    echo json_encode($result);
} else if ($method === 'GET' && $action === 'get_user') {
    $userId = isset($_GET['id']) ? $_GET['id'] : '';
    $userData = $user->getUser($userId);
    
    if ($userData) {
        echo json_encode($userData);
    } else {
        http_response_code(404);
        echo json_encode(['error' => 'User not found']);
    }
} else if ($method === 'GET' && $action === 'get_all') {
    $users = $user->getAllUsers();
    echo json_encode($users);
} else if ($method === 'POST' && $action === 'create') {
    $data = json_decode(file_get_contents("php://input"), true);
    if ($user->createUser($data)) {
        echo json_encode(['success' => true, 'message' => 'User created']);
    } else {
        http_response_code(500);
        echo json_encode(['error' => 'Failed to create user']);
    }
} else if ($method === 'POST' && $action === 'update_pin') {
    $data = json_decode(file_get_contents("php://input"), true);
    if (!isset($data['id']) || !isset($data['pin'])) {
        http_response_code(400);
        echo json_encode(['error' => 'Missing data']);
        exit;
    }
    if ($user->updateUserPin($data['id'], $data['pin'])) {
        echo json_encode(['success' => true]);
    } else {
        http_response_code(500);
        echo json_encode(['error' => 'Failed to update pin']);
    }
} else if ($method === 'POST' && $action === 'delete') {
    $data = json_decode(file_get_contents("php://input"), true);
    if (!isset($data['id'])) {
        http_response_code(400);
        echo json_encode(['error' => 'Missing user ID']);
        exit;
    }
    if ($user->deleteUserSoft($data['id'])) {
        echo json_encode(['success' => true]);
    } else {
        http_response_code(500);
        echo json_encode(['error' => 'Failed to delete user']);
    }
} else if ($method === 'POST' && $action === 'update_profile') {
    $data = json_decode(file_get_contents("php://input"), true);
    if (!isset($data['id'])) {
        http_response_code(400);
        echo json_encode(['error' => 'Missing user ID']);
        exit;
    }
    if ($user->updateUserProfile($data['id'], $data)) {
        echo json_encode(['success' => true]);
    } else {
        http_response_code(500);
        echo json_encode(['error' => 'Failed to update profile']);
    }
} else if ($method === 'GET' && $action === 'repair') {
    // This is an emergency fix to ensure the default admin user exists
    $adminData = [
        'id' => 'admin',
        'name' => 'System Admin',
        'role' => 'admin',
        'pin' => '1234',
        'email' => 'admin@system.lk',
        'phone' => '000-0000000'
    ];
    // Check if exists
    if (!$user->getUser('admin')) {
        $user->createUser($adminData);
        echo json_encode(['success' => true, 'message' => 'Admin user restored. Use PIN 1234']);
    } else {
        echo json_encode(['success' => true, 'message' => 'Admin user already exists.']);
    }
} else {
    http_response_code(400);
    echo json_encode(['error' => 'Invalid action']);
}
?>
