<?php
require_once __DIR__ . '/../../../Models/AdPackage.php';
require_once __DIR__ . '/../../../Models/VendorAd.php';

class AdController {
    public function packages() {
        $packageModel = new AdPackage();
        
        $page = isset($_GET['p']) ? (int)$_GET['p'] : 1;
        $perPage = 10;
        
        $result = $packageModel->paginatePackages($page, $perPage);
        $packages = $result['data'];
        
        $total = $result['total'];
        $totalPages = ceil($total / $perPage);

        require __DIR__ . '/../../../../views/admin/ads/packages.php';
    }

    public function vendors() {
        $adModel = new VendorAd();
        
        $page = isset($_GET['p']) ? (int)$_GET['p'] : 1;
        $perPage = 10;
        
        $result = $adModel->paginateWithDetails($page, $perPage);
        $ads = $result['data'];
        
        $total = $result['total'];
        $totalPages = ceil($total / $perPage);

        require __DIR__ . '/../../../../views/admin/ads/vendors.php';
    }

    public function storePackage() {
        $packageModel = new AdPackage();
        $data = [
            'name_en' => $_POST['name_en'],
            'name_ar' => $_POST['name_ar'],
            'price' => $_POST['price'],
            'duration_days' => $_POST['duration_days'],
            'status' => 'active'
        ];
        $packageModel->insert($data);
        header("Location: ?page=ad_packages&success=Package added");
    }

    public function deletePackage() {
        $packageModel = new AdPackage();
        $id = $_GET['id'] ?? 0;
        
        // Safety Check: Verify if any vendor is using this package
        $db = Database::getInstance();
        $stmt = $db->prepare("SELECT COUNT(*) FROM vendor_ads WHERE package_id = ?");
        $stmt->execute([$id]);
        $count = $stmt->fetchColumn();
        
        if ($count > 0) {
            header("Location: ?page=ad_packages&error=Cannot delete ad package because it is actively used by some vendor advertisements. Please deactivate the package instead!");
            exit;
        }
        
        $packageModel->delete($id);
        header("Location: ?page=ad_packages&success=Package deleted");
    }

    public function updatePackage() {
        $packageModel = new AdPackage();
        $id = $_POST['id'] ?? 0;
        
        if ($id) {
            $data = [
                'name_en' => $_POST['name_en'],
                'name_ar' => $_POST['name_ar'],
                'price' => $_POST['price'],
                'duration_days' => $_POST['duration_days'],
                'status' => $_POST['status'] ?? 'active'
            ];
            $packageModel->update($id, $data);
            header("Location: ?page=ad_packages&success=Package updated");
        } else {
            header("Location: ?page=ad_packages&error=Invalid package ID");
        }
        exit;
    }
}
