<?php
/**
 * Admin Authentication and Management System
 */

require_once 'Database.php';
require_once 'Logger.php';

class AdminAuth {
    private $db;
    
    public function __construct() {
        $this->db = Database::getInstance();
    }
    
    /**
     * Create admin user
     */
    public function createAdmin($userData) {
        // Validate input
        if (empty($userData['username']) || empty($userData['email']) || empty($userData['password'])) {
            throw new Exception('Username, email, and password are required');
        }
        
        // Hash password
        $passwordHash = password_hash($userData['password'], PASSWORD_DEFAULT);
        
        $adminData = [
            'username' => $userData['username'],
            'email' => $userData['email'],
            'password_hash' => $passwordHash,
            'full_name' => $userData['full_name'] ?? $userData['username'],
            'role' => $userData['role'] ?? 'admin'
        ];
        
        try {
            $this->db->insert('admin_users', $adminData);
            Logger::info('Admin user created', ['username' => $userData['username']]);
            return true;
        } catch (Exception $e) {
            Logger::error('Failed to create admin user', [
                'username' => $userData['username'],
                'error' => $e->getMessage()
            ]);
            throw new Exception('Failed to create admin user: ' . $e->getMessage());
        }
    }
    
    /**
     * Authenticate admin user
     */
    public function authenticate($username, $password) {
        try {
            $admin = $this->db->fetch(
                'SELECT * FROM admin_users WHERE username = ? AND is_active = TRUE',
                [$username]
            );
            
            if (!$admin) {
                Logger::warning('Admin login attempt - user not found', ['username' => $username]);
                return false;
            }
            
            if (!password_verify($password, $admin['password_hash'])) {
                Logger::warning('Admin login attempt - invalid password', ['username' => $username]);
                return false;
            }
            
            // Update last login
            $this->db->update(
                'admin_users',
                ['last_login' => date('Y-m-d H:i:s')],
                'id = ?',
                [$admin['id']]
            );
            
            Logger::info('Admin login successful', ['username' => $username]);
            
            // Remove password hash from session data
            unset($admin['password_hash']);
            
            return $admin;
            
        } catch (Exception $e) {
            Logger::error('Admin authentication failed', [
                'username' => $username,
                'error' => $e->getMessage()
            ]);
            return false;
        }
    }
    
    /**
     * Get all admin users
     */
    public function getAllAdmins() {
        try {
            return $this->db->fetchAll(
                'SELECT id, username, email, full_name, role, is_active, last_login, created_at 
                 FROM admin_users 
                 ORDER BY created_at DESC'
            );
        } catch (Exception $e) {
            Logger::error('Failed to get admin users', ['error' => $e->getMessage()]);
            return [];
        }
    }
    
    /**
     * Update admin user
     */
    public function updateAdmin($adminId, $userData) {
        $updateData = [];
        
        // Only update provided fields
        if (isset($userData['email'])) {
            $updateData['email'] = $userData['email'];
        }
        if (isset($userData['full_name'])) {
            $updateData['full_name'] = $userData['full_name'];
        }
        if (isset($userData['role'])) {
            $updateData['role'] = $userData['role'];
        }
        if (isset($userData['is_active'])) {
            $updateData['is_active'] = $userData['is_active'];
        }
        if (isset($userData['password']) && !empty($userData['password'])) {
            $updateData['password_hash'] = password_hash($userData['password'], PASSWORD_DEFAULT);
        }
        
        if (empty($updateData)) {
            return true; // Nothing to update
        }
        
        try {
            $this->db->update('admin_users', $updateData, 'id = ?', [$adminId]);
            Logger::info('Admin user updated', ['admin_id' => $adminId]);
            return true;
        } catch (Exception $e) {
            Logger::error('Failed to update admin user', [
                'admin_id' => $adminId,
                'error' => $e->getMessage()
            ]);
            throw new Exception('Failed to update admin user: ' . $e->getMessage());
        }
    }
    
    /**
     * Delete admin user
     */
    public function deleteAdmin($adminId) {
        try {
            $result = $this->db->delete('admin_users', 'id = ?', [$adminId]);
            if ($result > 0) {
                Logger::info('Admin user deleted', ['admin_id' => $adminId]);
                return true;
            }
            return false;
        } catch (Exception $e) {
            Logger::error('Failed to delete admin user', [
                'admin_id' => $adminId,
                'error' => $e->getMessage()
            ]);
            throw new Exception('Failed to delete admin user: ' . $e->getMessage());
        }
    }
    
    /**
     * Check if admin table exists
     */
    public function adminTableExists() {
        return $this->db->tableExists('admin_users');
    }
    
    /**
     * Initialize admin system
     */
    public function initializeAdminSystem() {
        if (!$this->adminTableExists()) {
            Logger::info('Admin table does not exist, creating schema');
            
            // Read and execute clean schema
            $schemaFile = __DIR__ . '/database_schema_clean.sql';
            if (file_exists($schemaFile)) {
                $schema = file_get_contents($schemaFile);
                $statements = array_filter(array_map('trim', explode(';', $schema)));
                
                foreach ($statements as $statement) {
                    if (!empty($statement)) {
                        try {
                            $this->db->exec($statement);
                        } catch (Exception $e) {
                            Logger::error('Schema execution failed', [
                                'statement' => $statement,
                                'error' => $e->getMessage()
                            ]);
                        }
                    }
                }
                
                Logger::info('Admin system initialized successfully');
                return true;
            } else {
                throw new Exception('Database schema file not found');
            }
        }
        
        return false; // Table already exists
    }
}

// Create global instance
$adminAuth = new AdminAuth();
