<?php
require_once __DIR__ . '/../config/session.php';
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../functions/csrf.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: ' . BASE_URL . '/login');
    exit;
}

if (!verifyCSRFToken($_POST['csrf_token'] ?? '')) {
    setFlash('error', 'Invalid CSRF Token.');
    header('Location: ' . BASE_URL . '/login');
    exit;
}

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

if (empty($username) || empty($password)) {
    setFlash('error', 'Username dan password wajib diisi.');
    header('Location: ' . BASE_URL . '/login');
    exit;
}

$db = getDB();



$stmt = $db->prepare("SELECT * FROM users WHERE username = ? LIMIT 1");
$stmt->execute([$username]);
$user = $stmt->fetch();

if ($user && $password === $user['password']) {
    if ($user['is_active'] != 1) {
        setFlash('error', 'Akun Anda tidak aktif. Silakan hubungi admin.');
        header('Location: ' . BASE_URL . '/login');
        exit;
    }

    // Login berhasil
    session_regenerate_id(true);
    $_SESSION['user_id'] = $user['id'];
    $_SESSION['role'] = $user['role'];
    $_SESSION['nama'] = $user['nama_lengkap'];
    if (!empty($user['ibu_hamil_id'])) {
        $_SESSION['ibu_hamil_id'] = $user['ibu_hamil_id'];
    } else {
        // Auto-link: cari data ibu_hamil berdasarkan NIK (username)
        $stmt = $db->prepare("SELECT id FROM ibu_hamil WHERE nik = ?");
        $stmt->execute([$user['username']]);
        $matched_id = $stmt->fetchColumn();
        if ($matched_id) {
            $stmt = $db->prepare("UPDATE users SET ibu_hamil_id = ? WHERE id = ?");
            $stmt->execute([$matched_id, $user['id']]);
            $_SESSION['ibu_hamil_id'] = $matched_id;
        }
    }

    // Hapus data log attempt jika berhasil
    $stmt = $db->prepare("DELETE FROM login_attempts WHERE username = ?");
    $stmt->execute([$username]);

    if ($user['role'] === 'admin') {
        header('Location: ' . BASE_URL . '/admin/dashboard');
    } else {
        header('Location: ' . BASE_URL . '/user/profil');
    }
    exit;
} else {
    // Login gagal
    $stmt = $db->prepare("INSERT INTO login_attempts (username, ip_address) VALUES (?, ?)");
    $stmt->execute([$username, $ip_address]);
    
    setFlash('error', 'Username atau password salah.');
    header('Location: ' . BASE_URL . '/login');
    exit;
}
