<?php
/**
 * auth.php - লগইন, রেজিস্ট্রেশন, লগআউট
 */
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/db.php';
session_name(SESSION_NAME);
session_start();

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

if ($action === 'register') {
    $email = trim($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';
    $name = trim($_POST['name'] ?? '');
    if (empty($email) || empty($password)) {
        $_SESSION['flash'] = ['type' => 'error', 'text' => 'ইমেইল ও পাসওয়ার্ড দিন।'];
        header('Location: index.php');
        exit;
    }
    $hash = password_hash($password, PASSWORD_DEFAULT);
    try {
        $st = $pdo->prepare('INSERT INTO users (email, password_hash, name) VALUES (?, ?, ?)');
        $st->execute([strtolower($email), $hash, $name ?: null]);
        $_SESSION['user_id'] = (int) $pdo->lastInsertId();
        $_SESSION['user_email'] = strtolower($email);
        $_SESSION['flash'] = ['type' => 'success', 'text' => 'রেজিস্ট্রেশন সফল।'];
        header('Location: index.php');
        exit;
    } catch (PDOException $e) {
        if (strpos($e->getMessage(), 'Duplicate') !== false) {
            $_SESSION['flash'] = ['type' => 'error', 'text' => 'এই ইমেইল ইতিমধ্যে আছে।'];
        } else {
            $_SESSION['flash'] = ['type' => 'error', 'text' => $e->getMessage()];
        }
        header('Location: index.php');
        exit;
    }
}

if ($action === 'login') {
    $email = trim($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';
    if (empty($email) || empty($password)) {
        $_SESSION['flash'] = ['type' => 'error', 'text' => 'ইমেইল ও পাসওয়ার্ড দিন।'];
        header('Location: index.php');
        exit;
    }
    $st = $pdo->prepare('SELECT id, email, password_hash FROM users WHERE email = ?');
    $st->execute([strtolower($email)]);
    $user = $st->fetch(PDO::FETCH_ASSOC);
    if (!$user || !password_verify($password, $user['password_hash'])) {
        $_SESSION['flash'] = ['type' => 'error', 'text' => 'ইমেইল বা পাসওয়ার্ড ভুল।'];
        header('Location: index.php');
        exit;
    }
    $_SESSION['user_id'] = (int) $user['id'];
    $_SESSION['user_email'] = $user['email'];
    $_SESSION['flash'] = ['type' => 'success', 'text' => 'লগইন সফল।'];
    header('Location: index.php');
    exit;
}

if ($action === 'logout') {
    $_SESSION = [];
    if (ini_get('session.use_cookies')) {
        $p = session_get_cookie_params();
        setcookie(session_name(), '', time() - 42000, $p['path'], $p['domain'], $p['secure'], $p['httponly']);
    }
    session_destroy();
    header('Location: index.php');
    exit;
}

header('Location: index.php');
exit;
