<?php
require_once __DIR__ . '/../../../Models/Vendor.php';

class VendorController {
    public function index() {
        $vendorModel = new Vendor();
        
        $page = isset($_GET['p']) ? (int)$_GET['p'] : 1;
        $perPage = 10;
        
        $searchTerm = $_GET['search'] ?? '';
        $status = $_GET['status'] ?? '';
        
        $filters = [];
        if ($status !== '') $filters['status'] = $status;
        
        $result = $vendorModel->searchPaginate(
            $page, 
            $perPage, 
            ['agency_name', 'email', 'phone'], 
            $searchTerm, 
            $filters
        );
        
        $vendors = $result['data'];
        $total = $result['total'];
        $totalPages = ceil($total / $perPage);

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

    public function bulkUpdate() {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') return;
        
        $ids = $_POST['ids'] ?? [];
        $action = $_POST['bulk_action'] ?? '';
        
        if (empty($ids) || empty($action)) {
            header("Location: ?page=vendors&error=No items or action selected");
            exit;
        }

        $vendorModel = new Vendor();
        $status = ($action === 'approve') ? 'approved' : (($action === 'suspend') ? 'suspended' : 'pending');
        
        foreach ($ids as $id) {
            $vendorModel->update($id, ['status' => $status]);
        }

        $this->logAction("Bulk " . $status, null, ['ids' => $ids]);

        header("Location: ?page=vendors&success=Bulk action completed");
        exit;
    }

    public function updateStatus() {
        $id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
        $status = $_GET['status'] ?? '';
        
        if ($id && in_array($status, ['pending', 'approved', 'rejected', 'suspended'])) {
            $vendorModel = new Vendor();
            $vendorModel->update($id, ['status' => $status]);
            
            $this->logAction("Update Status to " . $status, $id);
            
            header("Location: ?page=vendors&success=Vendor status updated successfully to " . $status);
            exit;
        }
        
        header("Location: ?page=vendors&error=Invalid status change request");
        exit;
    }

    public function toggleFeatured() {
        $id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
        if ($id) {
            $vendorModel = new Vendor();
            $vendor = $vendorModel->find($id);
            if ($vendor) {
                $newFeatured = $vendor['is_featured'] ? 0 : 1;
                $vendorModel->update($id, ['is_featured' => $newFeatured]);
                $this->logAction("Toggle Featured to " . $newFeatured, $id);
                header("Location: ?page=vendors&success=Vendor featured status updated successfully");
                exit;
            }
        }
        header("Location: ?page=vendors&error=Invalid vendor ID");
        exit;
    }

    public function toggleVerified() {
        $id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
        if ($id) {
            $vendorModel = new Vendor();
            $vendor = $vendorModel->find($id);
            if ($vendor) {
                $newVerified = $vendor['is_verified'] ? 0 : 1;
                $vendorModel->update($id, ['is_verified' => $newVerified]);
                $this->logAction("Toggle Verified to " . $newVerified, $id);
                header("Location: ?page=vendors&success=Vendor verification / insurance status updated successfully");
                exit;
            }
        }
        header("Location: ?page=vendors&error=Invalid vendor ID");
        exit;
    }

    private function logAction($action, $targetId = null, $details = null) {
        require_once __DIR__ . '/../../../Models/AuditLog.php';
        (new AuditLog())->log($action, 'vendors', $targetId, $details);
    }
}
