<?php
require_once __DIR__ . '/../models/Vehicle.php';
require_once __DIR__ . '/../models/Service.php';

class CustomerController {
    public function portal($f3) {
        $f3->set('is_impersonating', isset($_SESSION['original_super_admin']));
        $f3->set('impersonating_company', isset($_SESSION['impersonating_company']) ? $_SESSION['impersonating_company'] : null);
        echo \Template::instance()->render('customer/portal.html');
    }
    
    public function lookup($f3) {
        header('Content-Type: application/json');
        
        $data = json_decode(file_get_contents('php://input'), true);
        $registrationNumber = $data['registration_number'] ?? '';
        
        if (empty($registrationNumber)) {
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'Registration number is required']);
            return;
        }
        
        $db = $f3->get('DB');
        $domainModel = new \Models\Vehicle($db);
        $serviceModel = new \Models\Service($db);
        
        $domain = $domainModel->findByRegistration($registrationNumber);
        
        if (!$domain) {
            http_response_code(404);
            echo json_encode(['success' => false, 'message' => 'Domain not found']);
            return;
        }
        
        $services = $serviceModel->findByVehicle($domain['id']);
        
        $nextService = null;
        $today = date('Y-m-d');
        foreach ($services as $service) {
            if (!empty($service['next_service_date']) && $service['next_service_date'] >= $today) {
                $nextService = $service;
                break;
            }
        }
        
        echo json_encode([
            'success' => true,
            'domain' => $domain,
            'services' => $services,
            'next_service' => $nextService
        ]);
    }
}
