<?php
/**
 * Admin Panel - Base Controller
 * Handles all admin-level operations and authentication
 */

namespace App\Controller\Admin;

use App\Classes\Currency\CurrencyManager;

class AdminController {
    protected $db;
    protected $currentAdmin;
    protected $currencyManager;
    
    public function __construct($db) {
        $this->db = $db;
        $this->currencyManager = CurrencyManager::getInstance();
        $this->verifyAdminAccess();
    }
    
    /**
     * Verify admin access - check session/token
     */
    protected function verifyAdminAccess() {
        session_start();
        
        if (!isset($_SESSION['admin_id']) || $_SESSION['user_type'] !== 'admin') {
            $this->redirect('/admin/login', 'Unauthorized access');
        }
        
        // Load current admin details
        $this->loadCurrentAdmin();
    }
    
    /**
     * Load current admin user details
     */
    protected function loadCurrentAdmin() {
        $stmt = $this->db->prepare('SELECT * FROM users WHERE id = ? AND account_type = "admin"');
        $stmt->execute([$_SESSION['admin_id']]);
        $this->currentAdmin = $stmt->fetch(\PDO::FETCH_ASSOC);
        
        if (!$this->currentAdmin) {
            session_destroy();
            $this->redirect('/admin/login', 'Session expired');
        }
    }
    
    /**
     * Render admin view
     */
    protected function render($view, $data = []) {
        $loader = new \Twig_Loader_Filesystem('app/views/admin');
        $twig = new \Twig_Environment($loader);
        
        // Add helper functions
        $twig->addFunction(new \Twig_SimpleFunction('currency', function($amount, $curr = null) {
            return $this->currencyManager->formatPrice($amount, $curr);
        }));
        
        $data['admin'] = $this->currentAdmin;
        $data['currencies'] = $this->currencyManager->getCurrencies();
        
        echo $twig->render($view . '.twig', $data);
    }
    
    /**
     * Redirect with message
     */
    protected function redirect($url, $message = '', $type = 'info') {
        if ($message) {
            $_SESSION['message'] = ['text' => $message, 'type' => $type];
        }
        header('Location: ' . $url);
        exit;
    }
    
    /**
     * Return JSON response
     */
    protected function json($data, $statusCode = 200) {
        header('Content-Type: application/json');
        http_response_code($statusCode);
        echo json_encode($data);
        exit;
    }
    
    /**
     * Get dashboard statistics
     */
    protected function getDashboardStats() {
        $stats = [];
        
        // Total users
        $stmt = $this->db->query('SELECT COUNT(*) as count FROM users');
        $stats['total_users'] = $stmt->fetch(\PDO::FETCH_ASSOC)['count'];
        
        // Total balance
        $stmt = $this->db->query('SELECT SUM(balance) as total FROM users');
        $stats['total_balance'] = $stmt->fetch(\PDO::FETCH_ASSOC)['total'] ?? 0;
        
        // Today's orders
        $stmt = $this->db->query('SELECT COUNT(*) as count FROM orders WHERE DATE(created_at) = CURDATE()');
        $stats['todays_orders'] = $stmt->fetch(\PDO::FETCH_ASSOC)['count'];
        
        // Today's revenue
        $stmt = $this->db->query('SELECT SUM(price) as total FROM orders WHERE DATE(created_at) = CURDATE() AND status IN ("completed", "processing")');
        $stats['todays_revenue'] = $stmt->fetch(\PDO::FETCH_ASSOC)['total'] ?? 0;
        
        // Pending payments
        $stmt = $this->db->query('SELECT COUNT(*) as count FROM payments WHERE status = "pending"');
        $stats['pending_payments'] = $stmt->fetch(\PDO::FETCH_ASSOC)['count'];
        
        // Active users (last 7 days)
        $stmt = $this->db->query('SELECT COUNT(DISTINCT user_id) as count FROM orders WHERE created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)');
        $stats['active_users_7d'] = $stmt->fetch(\PDO::FETCH_ASSOC)['count'];
        
        return $stats;
    }
    
    /**
     * Log admin action
     */
    protected function logAdminAction($action, $details = '') {
        $stmt = $this->db->prepare('
            INSERT INTO admin_logs (admin_id, action, details, ip_address, created_at) 
            VALUES (?, ?, ?, ?, NOW())
        ');
        
        $stmt->execute([
            $this->currentAdmin['id'],
            $action,
            $details,
            $_SERVER['REMOTE_ADDR'] ?? 'unknown'
        ]);
    }
}
?>
