<?php
/**
 * REST API - Authentication Handler
 * Handles user registration, login, and password reset
 */

// Enable CORS
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
header('Content-Type: application/json; charset=utf-8');

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

// Load configuration
$config = require __DIR__.'/../app/config.php';

try {
    $conn = new PDO(
        "mysql:host=".$config["db"]["host"].";dbname=".$config["db"]["name"].";charset=".$config["db"]["charset"],
        $config["db"]["user"],
        $config["db"]["pass"]
    );
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Database connection failed']);
    exit();
}

// Parse request path - get action from URL parameter or PATH_INFO
$action = $_GET['action'] ?? (isset($_SERVER['PATH_INFO']) ? trim($_SERVER['PATH_INFO'], '/') : '');

// API route handlers
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    
    if ($action === 'register') {
        handleRegister($conn);
    } elseif ($action === 'login') {
        handleLogin($conn);
    } else {
        http_response_code(404);
        echo json_encode(['success' => false, 'message' => 'Endpoint not found']);
    }
} else {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
}

/**
 * Handle user registration
 */
function handleRegister($db) {
    try {
        // Get POST data
        $full_name = isset($_POST['full_name']) ? trim($_POST['full_name']) : '';
        $email = isset($_POST['email']) ? trim(strtolower($_POST['email'])) : '';
        $username = isset($_POST['username']) ? trim($_POST['username']) : '';
        $password = isset($_POST['password']) ? $_POST['password'] : '';
        
        // Validate required fields
        if (empty($full_name) || empty($email) || empty($username) || empty($password)) {
            http_response_code(400);
            echo json_encode([
                'success' => false,
                'message' => 'All fields are required'
            ]);
            return;
        }
        
        // Validate email format
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            http_response_code(400);
            echo json_encode([
                'success' => false,
                'message' => 'Invalid email format'
            ]);
            return;
        }
        
        // Validate username (alphanumeric, 3-20 chars)
        if (!preg_match('/^[a-zA-Z0-9_]{3,20}$/', $username)) {
            http_response_code(400);
            echo json_encode([
                'success' => false,
                'message' => 'Username must be 3-20 characters (letters, numbers, underscore only)'
            ]);
            return;
        }
        
        // Validate password strength (min 6 chars)
        if (strlen($password) < 6) {
            http_response_code(400);
            echo json_encode([
                'success' => false,
                'message' => 'Password must be at least 6 characters'
            ]);
            return;
        }
        
        // Check if username already exists
        $stmt = $db->prepare('SELECT client_id FROM clients WHERE username = ?');
        $stmt->execute([$username]);
        if ($stmt->fetch()) {
            http_response_code(409);
            echo json_encode([
                'success' => false,
                'message' => 'Username already taken'
            ]);
            return;
        }
        
        // Check if email already exists
        $stmt = $db->prepare('SELECT client_id FROM clients WHERE email = ?');
        $stmt->execute([$email]);
        if ($stmt->fetch()) {
            http_response_code(409);
            echo json_encode([
                'success' => false,
                'message' => 'Email already registered'
            ]);
            return;
        }
        
        // Generate API key and referral code
        $apikey = md5(uniqid() . time());
        $ref_code = bin2hex(random_bytes(3));
        
        // Hash password
        $hashed_password = md5($password);
        
        // Insert new user
        $stmt = $db->prepare('
            INSERT INTO clients (
                name, username, email, password, status, apikey, ref_code,
                balance, spent, register_date, email_type, lang,
                currency_type, client_type
            ) VALUES (
                ?, ?, ?, ?, ?, ?, ?,
                ?, ?, NOW(), ?, ?,
                ?, ?
            )
        ');
        
        $result = $stmt->execute([
            $full_name,           // name
            $username,            // username
            $email,               // email
            $hashed_password,     // password
            'active',             // status
            $apikey,              // apikey
            $ref_code,            // ref_code
            '0.00',               // balance
            '0.00',               // spent
            2,                    // email_type
            'en',                 // lang
            'UGX',                // currency_type (default)
            0                     // client_type (0 = regular, 1 = inactive)
        ]);
        
        if ($result) {
            $user_id = $db->lastInsertId();
            
            http_response_code(201);
            echo json_encode([
                'success' => true,
                'message' => 'Registration successful! You can now login.',
                'user_id' => $user_id,
                'username' => $username
            ]);
        } else {
            http_response_code(500);
            echo json_encode([
                'success' => false,
                'message' => 'Registration failed'
            ]);
        }
        
    } catch (Exception $e) {
        error_log('Registration Error: ' . $e->getMessage());
        http_response_code(500);
        echo json_encode([
            'success' => false,
            'message' => 'An error occurred during registration'
        ]);
    }
}

/**
 * Handle user login
 */
function handleLogin($db) {
    try {
        $username = isset($_POST['username']) ? trim($_POST['username']) : '';
        $password = isset($_POST['password']) ? $_POST['password'] : '';
        
        if (empty($username) || empty($password)) {
            http_response_code(400);
            echo json_encode([
                'success' => false,
                'message' => 'Username and password are required'
            ]);
            return;
        }
        
        // Find user by username or email
        $stmt = $db->prepare('
            SELECT client_id, username, name, email, password, status, balance, currency_type
            FROM clients
            WHERE (username = ? OR email = ?)
            LIMIT 1
        ');
        $stmt->execute([$username, $username]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$user) {
            http_response_code(401);
            echo json_encode([
                'success' => false,
                'message' => 'Invalid username or password'
            ]);
            return;
        }
        
        // Verify password
        if (md5($password) !== $user['password']) {
            http_response_code(401);
            echo json_encode([
                'success' => false,
                'message' => 'Invalid username or password'
            ]);
            return;
        }
        
        // Check if account is active
        if ($user['status'] !== 'active') {
            http_response_code(403);
            echo json_encode([
                'success' => false,
                'message' => 'Your account is not active. Contact support.'
            ]);
            return;
        }
        
        // Start session (if not already started)
        if (session_status() === PHP_SESSION_NONE) {
            session_start();
        }
        $_SESSION['msmbilisim_userlogin'] = 1;
        $_SESSION['msmbilisim_userid'] = $user['client_id'];
        $_SESSION['msmbilisim_userpass'] = $user['password'];
        $_SESSION['user_name'] = $user['name'];
        $_SESSION['user_balance'] = $user['balance'];
        
        // Set cookies
        setcookie('u_id', $user['client_id'], time() + (86400 * 30), '/');
        setcookie('u_password', $user['password'], time() + (86400 * 30), '/');
        setcookie('u_login', 'ok', time() + (86400 * 30), '/');
        
        http_response_code(200);
        echo json_encode([
            'success' => true,
            'message' => 'Login successful',
            'user_id' => $user['client_id'],
            'username' => $user['username'],
            'balance' => $user['balance'],
            'redirect' => '/'
        ]);
        
    } catch (Exception $e) {
        error_log('Login Error: ' . $e->getMessage());
        http_response_code(500);
        echo json_encode([
            'success' => false,
            'message' => 'An error occurred during login'
        ]);
    }
}
?>
