<?php
require_once __DIR__ . '/../config/config.php';
if (session_status() == PHP_SESSION_NONE && !headers_sent()) {
    session_start();
}
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/functions.php';

class AdminAuth {
    private $db;
    private $functions;
    
    public function __construct() {
        global $functions;
        $this->functions = $functions;
        $this->db = Database::getInstance()->getConnection();
    }
    
    // Admin Login
    public function login($data) {
        $username = $this->functions->sanitize($data['username']);
        $password = $data['password'];
        
        if (empty($username) || empty($password)) {
            return ['success' => false, 'message' => 'Username and password are required'];
        }
        
        $stmt = $this->db->prepare("SELECT * FROM admin_users WHERE username = ?");
        $stmt->execute([$username]);
        
        if ($stmt->rowCount() == 1) {
            $admin = $stmt->fetch();
            
            if (password_verify($password, $admin['password'])) {
                // Update last login
                $update = $this->db->prepare("UPDATE admin_users SET last_login = NOW() WHERE id = ?");
                $update->execute([$admin['id']]);
                
                // Set session
                $_SESSION['admin_id'] = $admin['id'];
                $_SESSION['admin_username'] = $admin['username'];
                $_SESSION['admin_role'] = $admin['role'];
                $_SESSION['user_role'] = 'admin';
                $_SESSION['logged_in'] = true;
                
                return ['success' => true, 'message' => 'Admin login successful'];
            }
        }
        return ['success' => false, 'message' => 'Invalid credentials'];
    }
    
    // Check if admin is logged in
    public function isLoggedIn() {
        return isset($_SESSION['admin_id']) && $_SESSION['logged_in'] === true && $_SESSION['user_role'] === 'admin';
    }
    
    // Get current admin ID
    public function getCurrentAdminId() {
        return $_SESSION['admin_id'] ?? null;
    }
    
    // Get current admin data
    public function getCurrentAdmin() {
        if (!$this->isLoggedIn()) return null;
        
        $stmt = $this->db->prepare("SELECT * FROM admin_users WHERE id = ?");
        $stmt->execute([$this->getCurrentAdminId()]);
        return $stmt->fetch();
    }
    
    // Admin Logout
    public function logout() {
        session_destroy();
        header("Location: login.php");
        exit();
    }
}

$adminAuth = new AdminAuth();