<?php
// --- SETUP AND INCLUDES ---
// Show all errors for debugging purposes
ini_set('display_errors', 1);
error_reporting(E_ALL);

// Set the content type to JSON for all responses
header("Content-Type: application/json; charset=UTF-8");

// Include required files
require_once '../config/cors.php';
require_once '../config/database.php';
// Note: Authentication files are included but the logic is commented out.
// require_once '../middleware/auth.php'; 
// require_once '../utils/jwt.php';

// --- DATABASE CONNECTION ---
$database = new Database();
$db = $database->getConnection();

// --- HTTP METHOD ROUTING ---
$method = $_SERVER['REQUEST_METHOD'];

switch ($method) {
    /**
     * Handles GET requests to fetch users.
     * Appends ?id={userId} to fetch a single user.
     */
    case 'GET':
        try {
            $userId = isset($_GET['id']) ? $_GET['id'] : null;
            
            if ($userId) {
                $stmt = $db->prepare("SELECT id, name, email, role, phone, email_verified, status, created_at FROM users WHERE id = :id");
                $stmt->bindParam(':id', $userId);
            } else {
                $stmt = $db->prepare("SELECT id, name, email, role, phone, email_verified, status, created_at FROM users ORDER BY created_at DESC");
            }
            
            $stmt->execute();
            
            if ($userId) {
                $user = $stmt->fetch(PDO::FETCH_ASSOC);
                if ($user) {
                    $user['status'] = (bool)$user['status']; // Convert 1/0 to true/false
                    echo json_encode($user);
                } else {
                    http_response_code(404);
                    echo json_encode(['error' => 'User not found.']);
                }
            } else {
                $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
                // Convert status from 1/0 to true/false for the frontend
                foreach ($users as &$user) {
                    $user['status'] = (bool)$user['status'];
                }
                echo json_encode(['users' => $users]);
            }
            
            http_response_code(200);

        } catch (PDOException $e) {
            http_response_code(500);
            echo json_encode(['error' => 'Database error: ' . $e->getMessage()]);
        }
        break;

    /**
     * Handles POST requests to create a new user.
     * Expects a JSON body with name, email, and password.
     */
    case 'POST':
        $data = json_decode(file_get_contents('php://input'), true);
        
        if (!isset($data['name']) || !isset($data['email']) || !isset($data['password'])) {
            http_response_code(400);
            echo json_encode(['error' => 'Missing required fields: name, email, password.']);
            exit;
        }
        
        try {
            $password_hash = password_hash($data['password'], PASSWORD_DEFAULT);
            $role = $data['role'] ?? 'user';
            $phone = $data['phone'] ?? null;
            $status = isset($data['status']) ? (int)$data['status'] : 1; // Default to 1 (active)

            $stmt = $db->prepare("INSERT INTO users (name, email, password_hash, role, phone, status) VALUES (:name, :email, :password_hash, :role, :phone, :status)");
            
            $stmt->execute([
                ':name' => htmlspecialchars(strip_tags($data['name'])),
                ':email' => filter_var($data['email'], FILTER_SANITIZE_EMAIL),
                ':password_hash' => $password_hash,
                ':role' => $role,
                ':phone' => $phone,
                ':status' => $status
            ]);
            
            http_response_code(201); // 201 Created
            echo json_encode(['message' => 'User created successfully', 'id' => $db->lastInsertId()]);
        } catch (PDOException $e) {
            // Check for duplicate email error
            if ($e->errorInfo[1] == 1062) {
                http_response_code(409); // 409 Conflict
                echo json_encode(['error' => 'An account with this email already exists.']);
            } else {
                http_response_code(500);
                echo json_encode(['error' => 'Failed to create user: ' . $e->getMessage()]);
            }
        }
        break;

    /**
     * Handles PUT requests to update an existing user.
     * Expects a JSON body with the user's ID and fields to update.
     */
    case 'PUT':
        $data = json_decode(file_get_contents('php://input'), true);
        
        if (!isset($data['id'])) {
            http_response_code(400);
            echo json_encode(['error' => 'User ID is required for update.']);
            exit;
        }

        try {
            // Dynamically build the update query
            $updates = [];
            $params = [':id' => $data['id']];
            
            if (isset($data['name'])) { $updates[] = "name = :name"; $params[':name'] = htmlspecialchars(strip_tags($data['name'])); }
            if (isset($data['email'])) { $updates[] = "email = :email"; $params[':email'] = filter_var($data['email'], FILTER_SANITIZE_EMAIL); }
            if (isset($data['password'])) { $updates[] = "password_hash = :password_hash"; $params[':password_hash'] = password_hash($data['password'], PASSWORD_DEFAULT); }
            if (isset($data['role'])) { $updates[] = "role = :role"; $params[':role'] = $data['role']; }
            if (isset($data['phone'])) { $updates[] = "phone = :phone"; $params[':phone'] = $data['phone']; }
            if (isset($data['status'])) { $updates[] = "status = :status"; $params[':status'] = (int)$data['status']; }
            
            if (empty($updates)) {
                http_response_code(400);
                echo json_encode(['error' => 'No fields provided to update.']);
                exit;
            }
            
            $sql = "UPDATE users SET " . implode(", ", $updates) . " WHERE id = :id";
            $stmt = $db->prepare($sql);
            $stmt->execute($params);

            // Use rowCount to check if a record was actually affected
            if ($stmt->rowCount() > 0) {
                http_response_code(200);
                echo json_encode(['message' => 'User updated successfully.']);
            } else {
                http_response_code(404); // Not Found
                echo json_encode(['error' => 'User not found or no changes were made.']);
            }
        } catch (PDOException $e) {
            http_response_code(500);
            echo json_encode(['error' => 'Failed to update user: ' . $e->getMessage()]);
        }
        break;

    /**
     * Handles DELETE requests to remove a user.
     * Expects a JSON body with the user's ID.
     */
    case 'DELETE':
        $data = json_decode(file_get_contents('php://input'), true);
        $userId = $data['id'] ?? null;

        if (!$userId) {
            http_response_code(400);
            echo json_encode(['error' => 'User ID is required in the request body.']);
            exit;
        }
        
        try {
            $stmt = $db->prepare("DELETE FROM users WHERE id = :id");
            $stmt->bindParam(':id', $userId);
            $stmt->execute();
            
            // Use rowCount to check if a record was actually deleted
            if ($stmt->rowCount() > 0) {
                http_response_code(200);
                echo json_encode(['message' => 'User deleted successfully.']);
            } else {
                http_response_code(404); // Not Found
                echo json_encode(['error' => 'User not found.']);
            }
        } catch (PDOException $e) {
             http_response_code(500);
            echo json_encode(['error' => 'Failed to delete user: ' . $e->getMessage()]);
        }
        break;

    /**
     * Handles any other HTTP method.
     */
    default:
        http_response_code(405); // Method Not Allowed
        echo json_encode(['error' => 'Method not allowed.']);
        break;
}
?>