<?php
class AuthController {
    private $pdo;
    public function __construct($pdo) {
        $this->pdo = $pdo;
        if(isset($_SESSION['user_id']) && !in_array($_GET['page'] ?? '', ['logout'])) {
            // Jika sudah login dan bukan halaman logout, redirect ke dashboard sesuai role
            $rolePage = ($_SESSION['role'] == 'pemilik_kapal') ? 'supir' : $_SESSION['role'];
            header("Location: ?page=" . $rolePage);
            exit;
        }
    }
    
    public function login() {
        if($_SERVER['REQUEST_METHOD'] == 'POST') {
            $email = $_POST['email'];
            $password = $_POST['password'];
            $stmt = $this->pdo->prepare("SELECT * FROM users WHERE email = ?");
            $stmt->execute([$email]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC);
            if($user && password_verify($password, $user['password'])) {
                $_SESSION['user_id'] = $user['id'];
                $_SESSION['role'] = $user['role'];
                $_SESSION['nama'] = $user['nama'];
                // ===== PERBAIKAN: Arahkan sesuai role =====
                if ($user['role'] == 'admin') {
                    header("Location: ?page=admin&action=dashboard");
                } elseif ($user['role'] == 'pemilik_kapal') {
                    header("Location: ?page=supir&action=dashboard");
                } elseif ($user['role'] == 'wisatawan') {
                    header("Location: ?page=wisatawan&action=dashboard");
                } else {
                    header("Location: ?page=home");
                }
                exit;
            } else {
                $error = "Email atau password salah.";
            }
        }
        require_once __DIR__ . '/../views/auth/login.php';
    }
    
    public function register() {
        if($_SERVER['REQUEST_METHOD'] == 'POST') {
            $nama = trim($_POST['nama'] ?? '');
            $email = trim($_POST['email'] ?? '');
            $no_hp = trim($_POST['no_hp'] ?? '');
            $password = $_POST['password'] ?? '';
            $konfirmasi = $_POST['konfirmasi_password'] ?? '';
            $role = $_POST['role'] ?? 'wisatawan';
            
            // Validasi
            $errors = [];
            if (empty($nama)) $errors[] = "Nama tidak boleh kosong.";
            if (empty($email)) $errors[] = "Email tidak boleh kosong.";
            if (empty($no_hp)) $errors[] = "Nomor HP tidak boleh kosong.";
            if (empty($password)) $errors[] = "Password tidak boleh kosong.";
            if ($password !== $konfirmasi) $errors[] = "Password dan konfirmasi password tidak sama!";
            
            if (empty($errors)) {
                // Cek duplikat
                $stmt = $this->pdo->prepare("SELECT * FROM users WHERE email = ? OR no_hp = ?");
                $stmt->execute([$email, $no_hp]);
                if($stmt->rowCount() > 0) {
                    $error = "Email atau No HP sudah terdaftar.";
                } else {
                    $hashed = password_hash($password, PASSWORD_DEFAULT);
                    $stmt = $this->pdo->prepare("INSERT INTO users (nama, email, password, no_hp, role) VALUES (?, ?, ?, ?, ?)");
                    $stmt->execute([$nama, $email, $hashed, $no_hp, $role]);
                    $success = "Registrasi berhasil! Silakan login.";
                }
            } else {
                $error = implode('<br>', $errors);
            }
        }
        require_once __DIR__ . '/../views/auth/register.php';
    }
    
    public function logout() {
        // Hapus semua session
        $_SESSION = array();
        
        // Hapus cookie 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"]
            );
        }
        
        // Hancurkan session
        session_destroy();
        
        // ===== REDIRECT KE LOGIN (BUKAN HOME) =====
        header("Location: ?page=login");
        exit;
    }
}
?>