<?php
session_start();
require_once '../config/database.php';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $username = mysqli_real_escape_string($conn, $_POST['username']);
    $password = $_POST['password'];

    $query = mysqli_query($conn, "SELECT * FROM users WHERE username = '$username'");
    
    if (mysqli_num_rows($query) > 0) {
        $user = mysqli_fetch_assoc($query);

        // 1. Verifikasi Password Hash
        if (password_verify($password, $user['password'])) {
            
            // 2. CEK STATUS BLOKIR (WAJIB ADA)
            if ($user['status_akun'] === 'blokir') {
                // Jika statusnya blokir, hentikan proses dan kirim notifikasi
                header("Location: ../auth/login_page.php?pesan=blocked");
                exit;
            }

            // 3. JIKA TIDAK DIBLOKIR, LANJUTKAN BUAT SESI
            $_SESSION['user_id']     = $user['id'];
            $_SESSION['nama']        = $user['nama'];
            $_SESSION['role']        = $user['role']; 
            $_SESSION['status_akun'] = $user['status_akun'];

            if ($user['role'] === 'admin') {
                header("Location: ../admin/index.php");
            } else {
                header("Location: ../index.php");
            }
            exit;
        } else {
            header("Location: ../auth/login_page.php?pesan=wrong_password");
            exit;
        }
    } else {
        header("Location: ../auth/login_page.php?pesan=not_found");
        exit;
    }
}