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

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

        require __DIR__ . '/../../../../views/admin/customers/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=customers&error=No items or action selected");
            exit;
        }

        $customerModel = new Customer();
        $status = ($action === 'block') ? 'blocked' : 'active';
        
        foreach ($ids as $id) {
            $customerModel->update($id, ['status' => $status]);
        }

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

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

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