<?php
error_reporting(E_ALL);

// Selalu include session.php dulu — supaya session_start hanya terjadi sekali
require_once __DIR__ . "/../config/session.php";
require_once __DIR__ . "/../config/koneksi.php";
require_once __DIR__ . "/../config/app.php";

// Cek method harus POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    setFlash('error', 'Akses tidak valid.');
    header("Location: " . base_url('/index.php'));
    exit;
}

$username = trim($_POST['username'] ?? '');
$password = trim($_POST['password'] ?? '');

if ($username === '' || $password === '') {
    setFlash('error', 'Username atau password tidak boleh kosong.');
    header("Location: " . base_url('/index.php'));
    exit;
}

// Query user
$sql = "SELECT * FROM pengurus WHERE username_pengurus = ? LIMIT 1";
$stmt = $koneksi->prepare($sql);
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 1) {
    
    $user = $result->fetch_assoc();

    // Sementara login masih plain password (belum hash)
    if ($password === $user['password_pengurus']) {

        // Set session user
        setSession('is_logged_in', true);
        setSession('pengurus_id', $user['id']);
        setSession('pengurus_nama', $user['nama']);
        setSession('pengurus_jabatan', $user['jabatan']);
        setSession('pengurus_foto', $user['foto']); // PENTING

        header("Location: " . base_url('/pages/web_dashboard/index.php'));
        exit;
    }

    // Kalau password salah
    setFlash('error', 'Password salah.');
    header("Location: " . base_url('/index.php'));
    exit;
}

// Kalau user tidak ditemukan
setFlash('error', 'Akun tidak ditemukan.');
header("Location: " . base_url('/index.php'));
exit;
