<?php
require_once __DIR__ . '/../models/User.php';
require_once __DIR__ . '/../models/Company.php';
require_once __DIR__ . '/../models/Vehicle.php';
require_once __DIR__ . '/../models/Customer.php';
require_once __DIR__ . '/../models/Service.php';
require_once __DIR__ . '/../models/Reminder.php';

class SuperAdminController {
    private function checkAuth($f3) {
        $isImpersonating = isset($_SESSION['original_super_admin']);
        $isSuperAdmin = isset($_SESSION['user']) && $_SESSION['user']['role'] === 'super_admin';
        
        if (!$isSuperAdmin && !$isImpersonating) {
            $f3->reroute('/login');
            return false;
        }
        return true;
    }
    
    private function logActivity($db, $action, $description, $userId = null) {
        $userId = $userId ? $userId : (isset($_SESSION['user']['id']) ? $_SESSION['user']['id'] : null);
        $ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : 'unknown';
        
        $db->exec(
            'INSERT INTO activity_logs (user_id, action, description, ip_address) VALUES (?, ?, ?, ?)',
            array($userId, $action, $description, $ip)
        );
    }
    
    public function dashboard($f3) {
        if (!$this->checkAuth($f3)) return;
        
        $db = $f3->get('DB');
        $companyModel = new \Models\Company($db);
        $userModel = new \Models\User($db);
        $vehicleModel = new \Models\Vehicle($db);
        $customerModel = new \Models\Customer($db);
        $serviceModel = new \Models\Service($db);
        $reminderModel = new \Models\Reminder($db);
        
        $allCompanies = $companyModel->findAll();
        $activeCompanies = array_filter($allCompanies, function($c) { return $c['is_active']; });
        
        $expiringSoon = $db->exec(
            "SELECT * FROM companies WHERE subscription_expiry IS NOT NULL AND subscription_expiry BETWEEN CURRENT_DATE AND CURRENT_DATE + INTERVAL '30 days' ORDER BY subscription_expiry"
        );
        
        $recentActivity = $db->exec(
            "SELECT al.*, u.name as user_name FROM activity_logs al LEFT JOIN users u ON al.user_id = u.id ORDER BY al.created_at DESC LIMIT 5"
        );
        
        $stats = array(
            'total_companies' => count($allCompanies),
            'active_companies' => count($activeCompanies),
            'total_users' => $userModel->countAll(),
            'total_vehicles' => $vehicleModel->countAll(),
            'total_customers' => $customerModel->countAll(),
            'total_services' => $serviceModel->countAll(),
            'total_reminders' => $reminderModel->countAll(),
            'expiring_soon' => count($expiringSoon)
        );
        
        $f3->set('stats', $stats);
        $f3->set('expiring_soon', $expiringSoon);
        $f3->set('recent_activity', $recentActivity);
        $f3->set('user', $_SESSION['user']);
        $f3->set('active_page', 'dashboard');
        echo \Template::instance()->render('super-admin/dashboard.html');
    }
    
    public function companies($f3) {
        if (!$this->checkAuth($f3)) return;
        
        $db = $f3->get('DB');
        $companyModel = new \Models\Company($db);
        $companies = $db->exec(
            "SELECT c.*, 
                    (SELECT COUNT(*) FROM users WHERE company_id = c.id) as user_count,
                    (SELECT COUNT(*) FROM customers WHERE company_id = c.id) as customer_count,
                    (SELECT u.id FROM users u INNER JOIN roles r ON u.role_id = r.id WHERE u.company_id = c.id AND r.name = 'company_admin' LIMIT 1) as admin_id,
                    (SELECT u.name FROM users u INNER JOIN roles r ON u.role_id = r.id WHERE u.company_id = c.id AND r.name = 'company_admin' LIMIT 1) as owner_name
             FROM companies c ORDER BY c.name"
        );
        
        foreach ($companies as &$company) {
            $company['slug'] = isset($company['slug']) ? $company['slug'] : '';
            $company['email'] = isset($company['email']) ? $company['email'] : '';
            $company['phone'] = isset($company['phone']) ? $company['phone'] : '';
            $company['owner_name'] = isset($company['owner_name']) ? $company['owner_name'] : '';
            $company['subscription_expiry'] = isset($company['subscription_expiry']) ? $company['subscription_expiry'] : null;
            $company['subscription_status'] = isset($company['subscription_status']) ? $company['subscription_status'] : '';
            $company['joined_date'] = isset($company['joined_date']) ? $company['joined_date'] : (isset($company['created_at']) ? $company['created_at'] : null);
            $company['is_expired'] = $company['subscription_expiry'] && strtotime($company['subscription_expiry']) < time();
            $company['is_expiring_soon'] = $company['subscription_expiry'] && 
                strtotime($company['subscription_expiry']) >= time() && 
                strtotime($company['subscription_expiry']) <= strtotime('+30 days');
        }
        
        $f3->set('companies', $companies);
        $f3->set('user', $_SESSION['user']);
        $f3->set('active_page', 'companies');
        echo \Template::instance()->render('super-admin/companies.html');
    }
    
    public function users($f3) {
        if (!$this->checkAuth($f3)) return;
        
        $db = $f3->get('DB');
        $users = $db->exec(
            "SELECT u.*, r.name as role_name, c.name as company_name 
             FROM users u 
             LEFT JOIN roles r ON u.role_id = r.id 
             LEFT JOIN companies c ON u.company_id = c.id 
             ORDER BY u.created_at DESC"
        );
        
        $stats = array(
            'total' => count($users),
            'company_admins' => count(array_filter($users, function($u) { return $u['role_name'] === 'company_admin'; })),
            'staff' => count(array_filter($users, function($u) { return $u['role_name'] === 'staff'; }))
        );
        
        $f3->set('users', $users);
        $f3->set('stats', $stats);
        $f3->set('user', $_SESSION['user']);
        $f3->set('active_page', 'users');
        echo \Template::instance()->render('super-admin/users.html');
    }
    
    public function subscriptions($f3) {
        if (!$this->checkAuth($f3)) return;
        
        $db = $f3->get('DB');
        $companies = $db->exec("SELECT * FROM companies ORDER BY subscription_expiry ASC NULLS LAST");
        
        foreach ($companies as &$company) {
            $company['is_expired'] = $company['subscription_expiry'] && strtotime($company['subscription_expiry']) < time();
            $company['is_expiring_soon'] = $company['subscription_expiry'] && 
                strtotime($company['subscription_expiry']) >= time() && 
                strtotime($company['subscription_expiry']) <= strtotime('+30 days');
        }
        
        $stats = array(
            'active' => count(array_filter($companies, function($c) { return isset($c['subscription_status']) && $c['subscription_status'] === 'active'; })),
            'expiring_soon' => count(array_filter($companies, function($c) { return isset($c['is_expiring_soon']) && $c['is_expiring_soon']; })),
            'expired' => count(array_filter($companies, function($c) { return isset($c['subscription_status']) && $c['subscription_status'] === 'expired'; })),
            'trial' => count(array_filter($companies, function($c) { return !isset($c['subscription_plan']) || $c['subscription_plan'] === 'trial' || $c['subscription_plan'] === ''; }))
        );
        
        $f3->set('companies', $companies);
        $f3->set('stats', $stats);
        $f3->set('user', $_SESSION['user']);
        $f3->set('active_page', 'subscriptions');
        echo \Template::instance()->render('super-admin/subscriptions.html');
    }
    
    public function activityLogs($f3) {
        if (!$this->checkAuth($f3)) return;
        
        $db = $f3->get('DB');
        $logs = $db->exec(
            "SELECT al.*, u.name as user_name, u.email as user_email 
             FROM activity_logs al 
             LEFT JOIN users u ON al.user_id = u.id 
             ORDER BY al.created_at DESC 
             LIMIT 100"
        );
        
        $f3->set('logs', $logs);
        $f3->set('user', $_SESSION['user']);
        $f3->set('active_page', 'activity-logs');
        echo \Template::instance()->render('super-admin/activity-logs.html');
    }
    
    public function reports($f3) {
        if (!$this->checkAuth($f3)) return;
        
        $db = $f3->get('DB');
        $customerModel = new \Models\Customer($db);
        $serviceModel = new \Models\Service($db);
        $reminderModel = new \Models\Reminder($db);
        
        $subscriptionStats = array(
            'premium' => $db->exec("SELECT COUNT(*) as count FROM companies WHERE subscription_plan = 'premium'")[0]['count'],
            'basic' => $db->exec("SELECT COUNT(*) as count FROM companies WHERE subscription_plan = 'basic'")[0]['count'],
            'trial' => $db->exec("SELECT COUNT(*) as count FROM companies WHERE subscription_plan IS NULL OR subscription_plan = 'trial' OR subscription_plan = ''")[0]['count']
        );
        
        $growthData = $db->exec(
            "SELECT TO_CHAR(created_at, 'Mon YYYY') as month, COUNT(*) as count 
             FROM companies 
             WHERE created_at >= CURRENT_DATE - INTERVAL '6 months'
             GROUP BY TO_CHAR(created_at, 'Mon YYYY'), DATE_TRUNC('month', created_at)
             ORDER BY DATE_TRUNC('month', created_at)"
        );
        
        $growthLabels = array();
        $growthCounts = array();
        foreach ($growthData as $row) {
            $growthLabels[] = $row['month'];
            $growthCounts[] = (int)$row['count'];
        }
        
        $topCompanies = $db->exec(
            "SELECT c.id, c.name,
                    (SELECT COUNT(*) FROM vehicles v INNER JOIN customers cu ON v.customer_id = cu.id WHERE cu.company_id = c.id) as vehicle_count,
                    (SELECT COUNT(*) FROM customers WHERE company_id = c.id) as customer_count,
                    (SELECT COUNT(*) FROM services s INNER JOIN vehicles v ON s.vehicle_id = v.id INNER JOIN customers cu ON v.customer_id = cu.id WHERE cu.company_id = c.id) as service_count
             FROM companies c
             ORDER BY vehicle_count DESC
             LIMIT 10"
        );
        
        $stats = array(
            'total_customers' => $customerModel->countAll(),
            'total_services' => $serviceModel->countAll(),
            'total_reminders' => $reminderModel->countAll()
        );
        
        $f3->set('stats', $stats);
        $f3->set('subscription_stats', $subscriptionStats);
        $f3->set('growth_labels', $growthLabels);
        $f3->set('growth_data', $growthCounts);
        $f3->set('top_companies', $topCompanies);
        $f3->set('user', $_SESSION['user']);
        $f3->set('active_page', 'reports');
        echo \Template::instance()->render('super-admin/reports.html');
    }
    
    public function settings($f3) {
        if (!$this->checkAuth($f3)) return;
        
        $db = $f3->get('DB');
        $settingsResult = $db->exec("SELECT key, value FROM system_settings");
        $settings = array();
        foreach ($settingsResult as $row) {
            $settings[$row['key']] = $row['value'];
        }
        
        $f3->set('settings', $settings);
        $f3->set('user', $_SESSION['user']);
        $f3->set('active_page', 'settings');
        echo \Template::instance()->render('super-admin/settings.html');
    }
    
    public function loginAs($f3) {
        if (!$this->checkAuth($f3)) return;
        
        header('Content-Type: application/json');
        $data = json_decode(file_get_contents('php://input'), true);
        $userId = isset($data['user_id']) ? $data['user_id'] : null;
        
        if (!$userId) {
            echo json_encode(array('success' => false, 'message' => 'User ID required'));
            return;
        }
        
        $db = $f3->get('DB');
        $userModel = new \Models\User($db);
        $targetUser = $userModel->findById($userId);
        
        if (!$targetUser) {
            echo json_encode(array('success' => false, 'message' => 'User not found'));
            return;
        }
        
        $_SESSION['original_super_admin'] = $_SESSION['user'];
        
        $_SESSION['user'] = array(
            'id' => $targetUser['id'],
            'name' => $targetUser['name'],
            'email' => $targetUser['email'],
            'role' => $targetUser['role_name'],
            'company_id' => $targetUser['company_id']
        );
        
        $this->logActivity($db, 'impersonate', 'Logged in as ' . $targetUser['name'] . ' (' . $targetUser['role_name'] . ')');
        
        $redirect = '/company';
        if ($targetUser['role_name'] === 'staff') {
            $redirect = '/staff';
        }
        
        echo json_encode(array('success' => true, 'redirect' => $f3->get('BASE_PATH') . $redirect));
    }
    
    public function returnToSuperAdmin($f3) {
        if (isset($_SESSION['original_super_admin'])) {
            $_SESSION['user'] = $_SESSION['original_super_admin'];
            unset($_SESSION['original_super_admin']);
            unset($_SESSION['impersonating_company']);
            
            $db = $f3->get('DB');
            $this->logActivity($db, 'return', 'Returned to Super Admin');
        }
        
        $f3->reroute('/super-admin');
    }
    
    public function loginAsCustomer($f3, $params) {
        if (!$this->checkAuth($f3)) return;
        
        $companyId = $params['id'];
        $db = $f3->get('DB');
        
        $company = $db->exec("SELECT * FROM companies WHERE id = ?", array($companyId));
        
        if (!$company) {
            $f3->reroute('/super-admin/companies');
            return;
        }
        
        $_SESSION['original_super_admin'] = $_SESSION['user'];
        $_SESSION['impersonating_company'] = $company[0];
        
        $this->logActivity($db, 'impersonate_customer', 'Logged in as customer for company: ' . $company[0]['name']);
        
        $f3->reroute('/customer-portal?company_id=' . $companyId);
    }
    
    public function getCompany($f3, $params) {
        if (!$this->checkAuth($f3)) return;
        
        header('Content-Type: application/json');
        $id = $params['id'];
        
        $db = $f3->get('DB');
        $companyModel = new \Models\Company($db);
        $company = $companyModel->findById($id);
        
        if ($company) {
            echo json_encode(array('success' => true, 'company' => $company));
        } else {
            http_response_code(404);
            echo json_encode(array('success' => false, 'message' => 'Company not found'));
        }
    }
    
    public function createCompany($f3) {
        if (!$this->checkAuth($f3)) return;
        
        header('Content-Type: application/json');
        $data = json_decode(file_get_contents('php://input'), true);
        
        $db = $f3->get('DB');
        $companyModel = new \Models\Company($db);
        
        try {
            $adminEmail = isset($data['admin_email']) && !empty($data['admin_email']) ? $data['admin_email'] : $data['email'];
            $adminName = isset($data['admin_name']) && !empty($data['admin_name']) ? $data['admin_name'] : $data['name'] . ' Admin';
            $adminPassword = isset($data['admin_password']) && !empty($data['admin_password']) ? $data['admin_password'] : null;
            
            if (empty($adminPassword) || strlen($adminPassword) < 6) {
                echo json_encode(array('success' => false, 'message' => 'Admin password is required and must be at least 6 characters'));
                return;
            }
            
            $existingUser = $db->exec("SELECT id FROM users WHERE email = ?", [$adminEmail]);
            if ($existingUser) {
                echo json_encode(array('success' => false, 'message' => 'A user with this email already exists'));
                return;
            }
            
            $db->exec("BEGIN");
            
            $companyId = $companyModel->create(array(
                'name' => $data['name'],
                'email' => $data['email'],
                'phone' => isset($data['phone']) ? $data['phone'] : null,
                'address' => isset($data['address']) ? $data['address'] : null
            ));
            
            $joinedDate = !empty($data['joined_date']) ? $data['joined_date'] : date('Y-m-d');
            $expiryDate = !empty($data['subscription_expiry']) ? $data['subscription_expiry'] : null;
            
            $db->exec(
                "UPDATE companies SET subscription_plan = ?, subscription_status = ?, joined_date = ?, subscription_expiry = ? WHERE id = ?",
                array('trial', 'active', $joinedDate, $expiryDate, $companyId)
            );
            
            $roleResult = $db->exec("SELECT id FROM roles WHERE name = 'company_admin'");
            $roleId = $roleResult ? $roleResult[0]['id'] : 2;
            
            $hashedPassword = password_hash($adminPassword, PASSWORD_DEFAULT);
            $db->exec(
                "INSERT INTO users (name, email, password, role_id, company_id, is_active, created_at) VALUES (?, ?, ?, ?, ?, true, CURRENT_TIMESTAMP)",
                [$adminName, $adminEmail, $hashedPassword, $roleId, $companyId]
            );
            
            $db->exec("COMMIT");
            
            $this->logActivity($db, 'create', 'Created company: ' . $data['name'] . ' with admin: ' . $adminEmail);
            
            echo json_encode(array('success' => true, 'message' => 'Company and admin user created successfully', 'admin_email' => $adminEmail));
        } catch (Exception $e) {
            $db->exec("ROLLBACK");
            http_response_code(500);
            echo json_encode(array('success' => false, 'message' => 'Failed to create company: ' . $e->getMessage()));
        }
    }
    
    public function updateCompany($f3, $params) {
        if (!$this->checkAuth($f3)) return;
        
        header('Content-Type: application/json');
        $data = json_decode(file_get_contents('php://input'), true);
        $id = $params['id'];
        
        $db = $f3->get('DB');
        $companyModel = new \Models\Company($db);
        
        try {
            $updateData = array(
                'name' => $data['name'],
                'email' => $data['email'],
                'phone' => $data['phone'],
                'address' => isset($data['address']) ? $data['address'] : null
            );
            
            if (isset($data['joined_date'])) {
                $updateData['joined_date'] = $data['joined_date'] ?: null;
            }
            if (isset($data['subscription_expiry'])) {
                $updateData['subscription_expiry'] = $data['subscription_expiry'] ?: null;
            }
            
            $companyModel->update($id, $updateData);
            
            $this->logActivity($db, 'update', 'Updated company ID: ' . $id);
            
            echo json_encode(array('success' => true, 'message' => 'Company updated successfully'));
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(array('success' => false, 'message' => 'Failed to update company'));
        }
    }
    
    public function deleteCompany($f3, $params) {
        if (!$this->checkAuth($f3)) return;
        
        header('Content-Type: application/json');
        $id = $params['id'];
        
        $db = $f3->get('DB');
        $companyModel = new \Models\Company($db);
        
        try {
            $company = $companyModel->findById($id);
            $companyModel->delete($id);
            
            $this->logActivity($db, 'delete', 'Deleted company: ' . ($company ? $company['name'] : $id));
            
            echo json_encode(array('success' => true, 'message' => 'Company deleted successfully'));
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(array('success' => false, 'message' => 'Failed to delete company'));
        }
    }
    
    public function toggleCompany($f3, $params) {
        if (!$this->checkAuth($f3)) return;
        
        header('Content-Type: application/json');
        $id = $params['id'];
        
        $db = $f3->get('DB');
        $companyModel = new \Models\Company($db);
        
        try {
            $company = $companyModel->findById($id);
            $companyModel->update($id, array('is_active' => !$company['is_active']));
            $updated = $companyModel->findById($id);
            
            $this->logActivity($db, 'update', 'Toggled company status: ' . $company['name']);
            
            echo json_encode(array('success' => true, 'is_active' => $updated['is_active']));
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(array('success' => false, 'message' => 'Failed to toggle company status'));
        }
    }
    
    public function updateSubscription($f3, $params) {
        if (!$this->checkAuth($f3)) return;
        
        header('Content-Type: application/json');
        $data = json_decode(file_get_contents('php://input'), true);
        $id = $params['id'];
        
        $db = $f3->get('DB');
        
        try {
            $db->exec(
                "UPDATE companies SET subscription_plan = ?, subscription_status = ?, subscription_expiry = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?",
                array($data['plan'], $data['status'], $data['expiry_date'] ? $data['expiry_date'] : null, $id)
            );
            
            $this->logActivity($db, 'update', 'Updated subscription for company ID: ' . $id);
            
            echo json_encode(array('success' => true, 'message' => 'Subscription updated successfully'));
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(array('success' => false, 'message' => 'Failed to update subscription'));
        }
    }
    
    public function renewSubscription($f3, $params) {
        if (!$this->checkAuth($f3)) return;
        
        header('Content-Type: application/json');
        $id = $params['id'];
        
        $db = $f3->get('DB');
        
        try {
            $newExpiry = date('Y-m-d', strtotime('+1 year'));
            $db->exec(
                "UPDATE companies SET subscription_status = 'active', subscription_expiry = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?",
                array($newExpiry, $id)
            );
            
            $this->logActivity($db, 'update', 'Renewed subscription for company ID: ' . $id);
            
            echo json_encode(array('success' => true, 'message' => 'Subscription renewed for 1 year'));
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(array('success' => false, 'message' => 'Failed to renew subscription'));
        }
    }
    
    public function saveSettings($f3) {
        if (!$this->checkAuth($f3)) return;
        
        header('Content-Type: application/json');
        $data = json_decode(file_get_contents('php://input'), true);
        
        $db = $f3->get('DB');
        
        try {
            foreach ($data as $key => $value) {
                $exists = $db->exec("SELECT 1 FROM system_settings WHERE key = ?", array($key));
                if ($exists) {
                    $db->exec("UPDATE system_settings SET value = ? WHERE key = ?", array($value, $key));
                } else {
                    $db->exec("INSERT INTO system_settings (key, value) VALUES (?, ?)", array($key, $value));
                }
            }
            
            $this->logActivity($db, 'update', 'Updated system settings');
            
            echo json_encode(array('success' => true, 'message' => 'Settings saved successfully'));
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(array('success' => false, 'message' => 'Failed to save settings'));
        }
    }
}
