<?php
/**
 * Admin Authentication Handler
 * 
 * Processes login requests for admin users
 */

// Start session
session_start();

// Include database configuration
require_once '../config/db_config.php';

// Function to sanitize user input
function sanitize_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}

// Check if form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Get username and password from the form
    $username = sanitize_input($_POST['username']);
    $password = sanitize_input($_POST['password']);
    
    // Validate input
    if (empty($username) || empty($password)) {
        $_SESSION['login_error'] = "Username dan password harus diisi";
        header("Location: login-admin.php");
        exit;
    }
    
    try {
        // Get database connection
        $db = getDbConnection();
        
        // Check if database connection is available
        if ($db === null) {
            $_SESSION['login_error'] = "Koneksi database gagal. Silakan coba lagi nanti atau hubungi administrator.";
            header("Location: login-admin.php");
            exit;
        }
        
        // Prepare and execute query
        $stmt = $db->prepare("SELECT * FROM users WHERE username = :username AND role = 'admin' LIMIT 1");
        $stmt->bindParam(':username', $username);
        $stmt->execute();
        
        // Check if user exists
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($user && password_verify($password, $user['password'])) {
            // Password is correct, create session
            $_SESSION['user_id'] = $user['user_id'];
            $_SESSION['username'] = $user['username'];
            $_SESSION['name'] = $user['name'];
            $_SESSION['role'] = $user['role'];
            
            // Redirect to admin dashboard
            header("Location: admin/dashboard.php");
            exit;
        } else {
            // Authentication failed
            $_SESSION['login_error'] = "Username atau password salah";
            header("Location: login-admin.php");
            exit;
        }
    } catch (PDOException $e) {
        // Database error
        error_log("Admin auth database error: " . $e->getMessage());
        $_SESSION['login_error'] = "Terjadi kesalahan sistem. Silakan coba lagi nanti.";
        header("Location: login-admin.php");
        exit;
    }
} else {
    // Not a POST request
    header("Location: login-admin.php");
    exit;
} 