<?php
require 'config.php';

// Enable error logging untuk debugging login
error_log("=== AUTH.PHP START ===");
error_log("Action: " . ($_GET['action'] ?? 'none'));

$action = $_GET['action'] ?? '';

if ($action == 'login') {
    $username = strtolower(trim($_POST['username'] ?? ''));
    $password = $_POST['password'] ?? '';

    error_log("Login attempt for username: $username");

    // Rate limiting per IP dan per username
    $ip = $_SERVER['REMOTE_ADDR'];
    if (!checkRateLimit($pdo, $ip, 'login', $username)) {
        error_log("Rate limit exceeded for IP: $ip, username: $username");
        http_response_code(429);
        echo json_encode(['error' => 'Terlalu banyak percobaan login. Coba lagi setelah 60 detik.']);
        exit;
    }

    if (strlen($username) < 3 || strlen($password) < 6) {
        error_log("Validation failed: username length " . strlen($username) . ", password length " . strlen($password));
        http_response_code(400);
        echo json_encode(['error' => 'Username min 3 karakter, Password min 6 karakter']);
        exit;
    }

    $stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?");
    $stmt->execute([$username]);
    $user = $stmt->fetch();
    if ($user && password_verify($password, $user['password_hash'])) {
        // Login sukses - hapus catatan rate limit
        $pdo->prepare("DELETE FROM rate_limits WHERE ip_address = ? AND action = 'login'")->execute([$ip]);
        $pdo->prepare("DELETE FROM rate_limits WHERE username = ? AND action = 'login'")->execute([$username]);

        // ========== PERBAIKAN SESSION FIXATION ==========
        $oldSessionId = session_id();
        if (!session_regenerate_id(true)) {
            error_log("session_regenerate_id failed for user: $username");
        } else {
            error_log("Session regenerated: old=$oldSessionId, new=" . session_id());
        }

        // Pastikan CSRF token tetap ada setelah session di-regenerasi
        if (empty($_SESSION['csrf_token'])) {
            $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
            error_log("CSRF token re-generated after login for user: $username");
        }

        $_SESSION['user_id'] = $user['id'];
        $_SESSION['username'] = $user['username'];
        $_SESSION['is_admin'] = $user['is_admin'];

        // Verifikasi session tersimpan
        error_log("Session after login: " . print_r($_SESSION, true));
        error_log("Session ID after login: " . session_id());

        echo json_encode(['status' => 'success', 'is_admin' => $user['is_admin']]);
        error_log("Login success response sent for user: $username");
    } else {
        // Login gagal - catat percobaan
        recordRateLimitAttempt($pdo, $ip, 'login', $username);
        error_log("Login failed for username: $username - invalid credentials");
        http_response_code(400);
        echo json_encode(['error' => 'Kredensial salah']);
    }
    exit;
}

if ($action == 'register') {
    $username = strtolower(trim($_POST['username'] ?? ''));
    $password = $_POST['password'] ?? '';
    $phoneNumber = trim($_POST['phone_number'] ?? '');

    error_log("Register attempt for username: $username, phone: $phoneNumber");

    // Rate limiting per IP untuk registrasi
    $ip = $_SERVER['REMOTE_ADDR'];
    if (!checkRateLimit($pdo, $ip, 'register')) {
        error_log("Register rate limit exceeded for IP: $ip");
        http_response_code(429);
        echo json_encode(['error' => 'Terlalu banyak percobaan pendaftaran. Coba lagi nanti.']);
        exit;
    }

    if (strlen($username) < 3 || strlen($password) < 6) {
        error_log("Register validation failed: username length " . strlen($username) . ", password length " . strlen($password));
        http_response_code(400);
        echo json_encode(['error' => 'Username minimal 3, password minimal 6 karakter']);
        exit;
    }

    // Validasi format nomor HP (Indonesia)
    if (empty($phoneNumber)) {
        error_log("Register failed: phone number empty");
        http_response_code(400);
        echo json_encode(['error' => 'Nomor HP harus diisi']);
        exit;
    }

    // Bersihkan spasi
    $phoneNumber = preg_replace('/\s+/', '', $phoneNumber);
    // Format yang diperbolehkan: 08xxxxxxxxxx, +628xxxxxxxxxx, 628xxxxxxxxxx
    if (!preg_match('/^(?:\+62|62|0)[0-9]{9,13}$/', $phoneNumber)) {
        error_log("Register failed: invalid phone format: $phoneNumber");
        http_response_code(400);
        echo json_encode(['error' => 'Format nomor HP tidak valid. Gunakan 08xxxxxxxxxx atau +628xxxxxxxxxx']);
        exit;
    }

    $hash = password_hash($password, PASSWORD_DEFAULT);
    try {
        $count = $pdo->query("SELECT COUNT(*) FROM users")->fetchColumn();
        $isAdmin = ($count == 0) ? 1 : 0;
        // Menyimpan phone_number, is_phone_verified = 1 (karena input user langsung dianggap valid)
        $stmt = $pdo->prepare("INSERT INTO users (username, password_hash, phone_number, is_phone_verified, is_admin, tickets) VALUES (?, ?, ?, 1, ?, 0)");
        $stmt->execute([$username, $hash, $phoneNumber, $isAdmin]);
        error_log("Register success for user: $username (is_admin=$isAdmin)");
        echo json_encode(['status' => 'success']);
    } catch (Exception $e) {
        // Pendaftaran gagal karena username atau nomor HP sudah ada
        recordRateLimitAttempt($pdo, $ip, 'register');
        if ($e->errorInfo[1] == 1062) {
            error_log("Register failed: duplicate username or phone for $username");
            echo json_encode(['error' => 'Username atau nomor HP sudah terdaftar']);
        } else {
            error_log("Register exception: " . $e->getMessage());
            echo json_encode(['error' => 'Gagal registrasi. Silakan coba lagi.']);
        }
        http_response_code(400);
    }
    exit;
}

if ($action == 'logout') {
    error_log("Logout action, destroying session with id: " . session_id());
    // Hancurkan session tanpa regenerasi ID (cukup destroy)
    session_destroy();
    header("Location: index.php");
    exit;
}

error_log("=== AUTH.PHP END (no action) ===");
?>