<?php
// api/auth.php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

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

require_once '../config/db.php';
require_once 'middleware.php';

$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? 'status';

try {
    switch ($method) {
        case 'GET':
            if ($action === 'status') {
                // Cek status login (Guest support)
                $user = optionalAuth();
                if ($user) {
                    echo json_encode([
                        'success' => true,
                        'logged_in' => true,
                        'user' => [
                            'id' => $user['id'],
                            'username' => $user['username'],
                            'role' => $user['role'],
                            'rumah_ibadah_id' => $user['rumah_ibadah_id'],
                            'no_telp' => $user['no_telp'] ?? ''
                        ]
                    ]);
                } else {
                    echo json_encode([
                        'success' => true,
                        'logged_in' => false,
                        'user' => null,
                        'message' => 'Guest Mode: Pengguna belum login.'
                    ]);
                }
            } else {
                http_response_code(400);
                echo json_encode(['success' => false, 'message' => 'Action GET tidak dikenal.']);
            }
            break;

        case 'POST':
            if ($action === 'login') {
                // Proses Login
                $body = json_decode(file_get_contents('php://input'), true) ?: $_POST;
                $username = trim($body['username'] ?? '');
                $password = trim($body['password'] ?? '');

                if (!$username || !$password) {
                    http_response_code(400);
                    echo json_encode(['success' => false, 'message' => 'Username dan Password wajib diisi.']);
                    exit;
                }

                // Cari user berdasarkan username
                $stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?");
                $stmt->execute([$username]);
                $user = $stmt->fetch();

                if ($user && password_verify($password, $user['password'])) {
                    // Simpan data penting ke session
                    $_SESSION['user'] = [
                        'id' => (int)$user['id'],
                        'username' => $user['username'],
                        'role' => $user['role'],
                        'rumah_ibadah_id' => $user['rumah_ibadah_id'] ? (int)$user['rumah_ibadah_id'] : null,
                        'no_telp' => $user['no_telp'] ?? ''
                    ];

                    echo json_encode([
                        'success' => true,
                        'message' => 'Login berhasil! Selamat datang, ' . $user['username'],
                        'user' => $_SESSION['user']
                    ]);
                } else {
                    http_response_code(401);
                    echo json_encode(['success' => false, 'message' => 'Username atau Password salah.']);
                }
            } elseif ($action === 'register') {
                // Proses Registrasi Mandiri (hanya untuk kontributor & koordinator)
                $body = json_decode(file_get_contents('php://input'), true) ?: $_POST;
                $username       = trim($body['username'] ?? '');
                $email          = trim($body['email'] ?? '');
                $password       = trim($body['password'] ?? '');
                $noTelp         = trim($body['no_telp'] ?? '');
                $role           = trim($body['role'] ?? '');
                $rumahIbadahId  = isset($body['rumah_ibadah_id']) && $body['rumah_ibadah_id'] !== '' ? (int)$body['rumah_ibadah_id'] : null;

                // Validasi field wajib
                if (!$username || !$email || !$password || !$noTelp || !$role) {
                    http_response_code(400);
                    echo json_encode(['success' => false, 'message' => 'Semua field wajib diisi (username, email, password, no_telp, role).']);
                    exit;
                }

                // Validasi panjang & kekuatan password
                if (strlen($password) < 6) {
                    http_response_code(400);
                    echo json_encode(['success' => false, 'message' => 'Password minimal 6 karakter.']);
                    exit;
                }

                // Validasi format email
                if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                    http_response_code(400);
                    echo json_encode(['success' => false, 'message' => 'Format email tidak valid.']);
                    exit;
                }

                // Whitelist role — HANYA kontributor dan koordinator yang boleh mendaftar sendiri
                $allowedRoles = ['kontributor', 'koordinator'];
                if (!in_array($role, $allowedRoles)) {
                    http_response_code(403);
                    echo json_encode(['success' => false, 'message' => 'Peran "' . $role . '" tidak diizinkan untuk registrasi mandiri.']);
                    exit;
                }

                // Koordinator wajib memilih rumah ibadah
                if ($role === 'koordinator' && !$rumahIbadahId) {
                    http_response_code(400);
                    echo json_encode(['success' => false, 'message' => 'Koordinator Rumah Ibadah wajib memilih rumah ibadah yang dikelola.']);
                    exit;
                }

                // Kontributor tidak boleh terikat ke rumah ibadah
                if ($role === 'kontributor') {
                    $rumahIbadahId = null;
                }

                // Cek duplikasi username
                $stmtCheck = $pdo->prepare("SELECT id FROM users WHERE username = ? LIMIT 1");
                $stmtCheck->execute([$username]);
                if ($stmtCheck->fetch()) {
                    http_response_code(409);
                    echo json_encode(['success' => false, 'message' => 'Username "' . $username . '" sudah terdaftar. Gunakan username lain.']);
                    exit;
                }

                // Cek duplikasi email
                $stmtCheck2 = $pdo->prepare("SELECT id FROM users WHERE email = ? LIMIT 1");
                $stmtCheck2->execute([$email]);
                if ($stmtCheck2->fetch()) {
                    http_response_code(409);
                    echo json_encode(['success' => false, 'message' => 'Email "' . $email . '" sudah terdaftar. Gunakan email lain.']);
                    exit;
                }

                // Validasi rumah ibadah ada di database (untuk koordinator)
                if ($role === 'koordinator' && $rumahIbadahId) {
                    $stmtIbadah = $pdo->prepare("SELECT id FROM rumah_ibadah WHERE id = ? LIMIT 1");
                    $stmtIbadah->execute([$rumahIbadahId]);
                    if (!$stmtIbadah->fetch()) {
                        http_response_code(400);
                        echo json_encode(['success' => false, 'message' => 'Rumah ibadah yang dipilih tidak valid atau tidak ditemukan.']);
                        exit;
                    }
                }

                // Hash password dengan bcrypt
                $hashedPassword = password_hash($password, PASSWORD_BCRYPT);

                // Simpan user baru ke database
                $stmtInsert = $pdo->prepare("INSERT INTO users (username, email, password, no_telp, role, rumah_ibadah_id) VALUES (?, ?, ?, ?, ?, ?)");
                $stmtInsert->execute([$username, $email, $hashedPassword, $noTelp, $role, $rumahIbadahId]);

                $roleLabel = $role === 'koordinator' ? 'Koordinator Rumah Ibadah' : 'Kontributor';
                echo json_encode([
                    'success'  => true,
                    'message'  => 'Registrasi berhasil! Selamat bergabung sebagai ' . $roleLabel . '. Silakan login dengan akun Anda.',
                    'username' => $username
                ]);

            } elseif ($action === 'logout') {
                // Proses Logout
                if (session_status() === PHP_SESSION_NONE) {
                    session_start();
                }
                
                // Hapus semua data session dan hancurkan
                $_SESSION = [];
                if (ini_get("session.use_cookies")) {
                    $params = session_get_cookie_params();
                    setcookie(session_name(), '', time() - 42000,
                        $params["path"], $params["domain"],
                        $params["secure"], $params["httponly"]
                    );
                }
                session_destroy();

                echo json_encode([
                    'success' => true,
                    'message' => 'Logout berhasil. Anda sekarang masuk sebagai Guest.'
                ]);
            } else {
                http_response_code(400);
                echo json_encode(['success' => false, 'message' => 'Action POST tidak dikenal.']);
            }
            break;

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