<?php
require_once __DIR__ . '/../includes/header_customer.php';
require_once __DIR__ . '/../includes/auth.php';
$pdo = require __DIR__ . '/../config/pdo.php';

if (is_logged_in()) {
    $role = current_user()['role'] ?? '';
    if ($role === 'customer') {
        redirect(base_url('public/index.php'));
    } elseif (in_array($role, ['admin', 'owner'], true)) {
        redirect(base_url('admin/dashboard.php'));
    }
}

$errors = [];
$email = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = trim($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';

    if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors['email'] = 'Email tidak valid.';
    }

    if ($password === '') {
        $errors['password'] = 'Password wajib diisi.';
    }

    if (!$errors) {
        $stmt = $pdo->prepare('SELECT id, name, email, password_hash, role, is_active FROM users WHERE email = ? LIMIT 1');
        $stmt->execute([$email]);
        $user = $stmt->fetch();

        if (!$user || !password_verify($password, $user['password_hash'])) {
            $errors['general'] = 'Email atau password salah.';
        } elseif ((int) $user['is_active'] !== 1) {
            $errors['general'] = 'Akun tidak aktif.';
        } elseif ($user['role'] !== 'customer') {
            $errors['general'] = 'Akun ini khusus admin/owner. Silakan login di halaman admin.';
        } else {
            login_user($user);
            redirect(base_url('public/index.php'));
        }
    }
}

// Header already included at top
?>

<section class="auth-card">
    <h2>Login Customer</h2>

    <?php if ($message = flash_message('success')): ?>
        <div class="alert success"><?= sanitize($message); ?></div>
    <?php endif; ?>

    <?php if (!empty($errors['general'])): ?>
        <div class="alert error"><?= sanitize($errors['general']); ?></div>
    <?php endif; ?>

    <form method="post">
        <label>Email</label>
        <input type="email" name="email" value="<?= sanitize($email); ?>" required>
        <?php if (!empty($errors['email'])): ?><small class="error"><?= sanitize($errors['email']); ?></small><?php endif; ?>

        <label>Password</label>
        <input type="password" name="password" required>
        <?php if (!empty($errors['password'])): ?><small class="error"><?= sanitize($errors['password']); ?></small><?php endif; ?>

        <button type="submit">Masuk</button>
        <p>Belum punya akun? <a href="<?= base_url('pages/register.php'); ?>">Daftar</a></p>
    </form>
</section>

<?php require_once __DIR__ . '/../includes/footer_customer.php'; ?>
