<?php
/**
 * Authentication API Endpoint
 */

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/constants.php';
require_once __DIR__ . '/../includes/Database.php';
require_once __DIR__ . '/../includes/Auth.php';
require_once __DIR__ . '/../includes/Cart.php';

header('Content-Type: application/json');

$auth = new Auth();
$cart = new Cart();
$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? '';

try {
    switch ($method) {
        case 'POST':
            $data = json_decode(file_get_contents('php://input'), true);

            if ($action === 'login') {
                $email = $data['email'] ?? '';
                $password = $data['password'] ?? '';
                $isAdmin = isset($data['is_admin']) && $data['is_admin'];

                if ($auth->login($email, $password, $isAdmin)) {
                    $user = $auth->getUser();
                    
                    // Handle cart merge for regular users
                    if (!$isAdmin && $user) {
                        $sessionId = $auth->getSessionId();
                        $sessionCart = $cart->getOrCreateCart(null, $sessionId);
                        $userCart = $cart->getOrCreateCart($user['id'], null);

                        // Check if both carts have items
                        $sessionItems = $cart->getCartItems($sessionCart['id']);
                        $userItems = $cart->getCartItems($userCart['id']);

                        if (!empty($sessionItems) && !empty($userItems)) {
                            // Both carts have items - return merge flag
                            echo json_encode([
                                'success' => true,
                                'user' => $user,
                                'needs_cart_merge' => true,
                                'session_cart_id' => $sessionCart['id'],
                                'user_cart_id' => $userCart['id']
                            ]);
                        } elseif (!empty($sessionItems)) {
                            // Only session cart has items - merge automatically
                            $cart->mergeCarts($sessionCart['id'], $userCart['id'], 'replace');
                            echo json_encode(['success' => true, 'user' => $user]);
                        } else {
                            // Only user cart or no items - use user cart
                            echo json_encode(['success' => true, 'user' => $user]);
                        }
                    } else {
                        echo json_encode(['success' => true, 'user' => $user]);
                    }
                } else {
                    http_response_code(401);
                    echo json_encode(['success' => false, 'message' => 'Invalid credentials']);
                }
            } elseif ($action === 'register') {
                $result = $auth->register($data);
                if ($result) {
                    $user = $auth->getUser();
                    echo json_encode(['success' => true, 'user' => $user]);
                } else {
                    http_response_code(400);
                    echo json_encode(['success' => false, 'message' => 'Registration failed']);
                }
            } elseif ($action === 'logout') {
                $auth->logout();
                echo json_encode(['success' => true]);
            }
            break;

        case 'GET':
            if ($action === 'check') {
                // Check if user is logged in
                if ($auth->isLoggedIn()) {
                    $user = $auth->getUser();
                    echo json_encode(['success' => true, 'logged_in' => true, 'user' => $user]);
                } else {
                    echo json_encode(['success' => true, 'logged_in' => false]);
                }
            }
            break;

        default:
            http_response_code(405);
            echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    }
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>

