<?php
// post/login.php
require_once '../config/config.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    redirect('../index.php');
}

 $username = $_POST['username'] ?? '';
 $password = $_POST['password'] ?? '';

if (empty($username) || empty($password)) {
    $_SESSION['error'] = 'Username dan password harus diisi!';
    redirect('../index.php');
}

try {
    $stmt = $pdo->prepare("
        SELECT u.*, t.nama_tema, t.warna_primary, t.warna_secondary, t.warna_accent,
               b.kode_bahasa, b.nama_bahasa
        FROM user u
        LEFT JOIN tema t ON u.id_tema = t.id_tema
        LEFT JOIN bahasa b ON u.id_bahasa = b.id_bahasa
        WHERE u.user_name = ?
    ");
    $stmt->execute([$username]);
    $user = $stmt->fetch();

    if (!$user) {
        $_SESSION['error'] = 'Username tidak ditemukan!';
        redirect('../index.php');
    }

    if (!password_verify($password, $user['password'])) {
        $_SESSION['error'] = 'Password salah!';
        redirect('../index.php');
    }

    // Update last login
    $updateStmt = $pdo->prepare("UPDATE user SET last_login = NOW() WHERE user_name = ?");
    $updateStmt->execute([$username]);

    // Set session
    $_SESSION['user'] = [
        'username' => $user['user_name'],
        'full_name' => $user['full_name'],
        'tema' => [
            'id' => $user['id_tema'],
            'nama' => $user['nama_tema'],
            'primary' => $user['warna_primary'],
            'secondary' => $user['warna_secondary'],
            'accent' => $user['warna_accent']
        ],
        'bahasa' => [
            'id' => $user['id_bahasa'],
            'kode' => $user['kode_bahasa'],
            'nama' => $user['nama_bahasa']
        ],
        'login_time' => time()
    ];

    // Regenerate session ID untuk security
    session_regenerate_id(true);

    redirect('../view/dashboard.php');

} catch (PDOException $e) {
    error_log("Login error: " . $e->getMessage());
    $_SESSION['error'] = 'Terjadi kesalahan sistem. Silakan coba lagi.';
    redirect('../index.php');
}
?>