<?php
require_once __DIR__ . '/../models/Lead.php';
require_once __DIR__ . '/../models/Customer.php';

class WizardController extends Controller
{
    public function index(): void
    {
        $this->view('home.wizard', ['title' => 'Project Request Wizard | Balorp Ventures']);
    }

    public function submit(): void
    {
        if (!$this->isPost()) {
            $this->redirect('/wizard');
        }

        $token = $_POST['csrf_token'] ?? '';
        if (!CSRF::validate($token)) {
            $this->respondWithJson(['success' => false, 'message' => 'Invalid CSRF token'], 403);
        }

        $isAjax = !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest';

        $services = $_POST['services'] ?? [];
        if (is_string($services)) {
            $services = [$services];
        }
        if (!is_array($services)) {
            $services = [];
        }
        $servicesStr = implode(',', array_filter(array_map('trim', $services)));

        $data = [
            'project_type' => trim((string)($_POST['project_type'] ?? '')),
            'property_type' => trim((string)($_POST['property_type'] ?? '')),
            'project_nature' => trim((string)($_POST['project_nature'] ?? $_POST['purpose'] ?? '')),
            'services' => $servicesStr,
            'project_size' => trim((string)($_POST['project_size'] ?? '')),
            'floor_area' => trim((string)($_POST['floor_area'] ?? '')),
            'region' => trim((string)($_POST['region'] ?? '')),
            'city' => trim((string)($_POST['city'] ?? '')),
            'area' => trim((string)($_POST['area'] ?? '')),
            'location' => trim(implode(', ', array_filter([trim((string)($_POST['area'] ?? '')), trim((string)($_POST['city'] ?? '')), trim((string)($_POST['region'] ?? ''))]))),
            'project_stage' => trim((string)($_POST['project_stage'] ?? '')),
            'timeline_start' => trim((string)($_POST['timeline_start'] ?? '')),
            'timeline_end' => trim((string)($_POST['timeline_end'] ?? '')),
            'site_visit' => trim((string)($_POST['site_visit'] ?? 'No')),
            'preferred_visit_date' => trim((string)($_POST['preferred_visit_date'] ?? $_POST['preferred_date'] ?? '')),
            'preferred_visit_time' => trim((string)($_POST['preferred_visit_time'] ?? $_POST['preferred_time'] ?? '')),
            'name' => trim((string)($_POST['full_name'] ?? $_POST['name'] ?? '')),
            'phone' => trim((string)($_POST['phone'] ?? '')),
            'whatsapp' => trim((string)($_POST['whatsapp'] ?? '')),
            'preferred_contact_method' => trim((string)($_POST['preferred_contact'] ?? $_POST['preferred_contact_method'] ?? '')),
            'email' => filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL) ?: '',
            'notes' => trim((string)($_POST['notes'] ?? '')),
        ];

        if (empty($data['name']) || empty($data['phone']) || empty($data['email']) || empty($data['location'])) {
            if ($isAjax) {
                $this->respondWithJson(['success' => false, 'message' => 'Please provide your name, phone, email, and project location.']);
            }

            $this->view('home.wizard', [
                'title' => 'Project Request Wizard | Balorp Ventures',
                'error' => 'Please provide your name, phone, email, and project location.',
            ]);
            return;
        }

        $uploadedFiles = [];
        if (!empty($_FILES['uploads']['name'][0])) {
            $uploadDir = __DIR__ . '/../../storage/uploads';
            if (!is_dir($uploadDir)) {
                mkdir($uploadDir, 0755, true);
            }
            foreach ($_FILES['uploads']['name'] as $idx => $name) {
                $tmp = $_FILES['uploads']['tmp_name'][$idx] ?? null;
                if ($tmp && is_uploaded_file($tmp)) {
                    $safe = time() . '_' . bin2hex(random_bytes(6)) . '_' . preg_replace('/[^a-zA-Z0-9_.-]/', '_', basename($name));
                    $target = $uploadDir . '/' . $safe;
                    if (move_uploaded_file($tmp, $target)) {
                        $uploadedFiles[] = 'storage/uploads/' . $safe;
                    }
                }
            }
        }

        $details = [];
        foreach (['project_type','property_type','services','project_size','floor_area','project_stage','timeline_start','timeline_end','site_visit','preferred_visit_date','preferred_visit_time','region','city','area','whatsapp','preferred_contact_method'] as $k) {
            if (!empty($data[$k])) {
                $details[] = ucfirst(str_replace('_', ' ', $k)) . ': ' . $data[$k];
            }
        }
        if (!empty($uploadedFiles)) {
            $details[] = 'Uploads: ' . implode(', ', $uploadedFiles);
        }
        if (!empty($details)) {
            $data['notes'] = trim(($data['notes'] ? $data['notes'] . "\n\n" : '') . implode("\n", $details));
        }

        $customerModel = new Customer();
        $leadModel = new Lead();
        $db = Database::connection();

        $db->beginTransaction();
        try {
            $customer = $customerModel->findByEmail($data['email']);
            if ($customer) {
                $customerId = (int)$customer['id'];
                $customerModel->updateContact($customerId, [
                    'name' => $data['name'],
                    'email' => $data['email'],
                    'phone' => $data['phone'],
                    'company' => $data['company'] ?? null,
                    'address' => $data['address'] ?? null,
                    'notes' => $data['notes'],
                ]);
            } else {
                $customerId = (int)$customerModel->create([
                    'name' => $data['name'],
                    'email' => $data['email'],
                    'phone' => $data['phone'],
                    'company' => $data['company'] ?? null,
                    'address' => $data['address'] ?? null,
                    'notes' => $data['notes'],
                ]);
            }

            if ($customerId <= 0) {
                throw new RuntimeException('Customer creation failed');
            }

            $data['customer_id'] = $customerId > 0 ? $customerId : null;
            $leadId = $leadModel->create($data);

            if (!$leadId) {
                throw new RuntimeException('Lead creation failed');
            }

            $db->commit();
        } catch (Throwable $e) {
            $db->rollBack();
            $leadId = null;
            error_log('Wizard submit error: ' . $e->getMessage());
        }

        $leadModel = new Lead();
        if ($leadId) {
            $reference = sprintf('BV-EST-%s-%05d', date('Y'), (int)$leadId);
            $extra = "Reference: {$reference}";
            if (!empty($uploadedFiles)) {
                $extra .= "\nUploads: " . implode(', ', $uploadedFiles);
            }
            $leadModel->appendNotes((int)$leadId, $extra);

            if ($isAjax) {
                $this->respondWithJson(['success' => true, 'reference' => $reference]);
            }

            $this->setFlash('success', 'Your estimate request has been submitted. Reference: ' . $reference);
            $this->redirect('/wizard');
        }

        if ($isAjax) {
            $this->respondWithJson(['success' => false, 'message' => 'Unable to submit your request. Please try again.']);
        }

        $this->view('home.wizard', ['title' => 'Project Request Wizard | Balorp Ventures', 'error' => 'Unable to submit your request. Please try again.']);
    }

    private function respondWithJson(array $payload, int $statusCode = 200): void
    {
        http_response_code($statusCode);
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode($payload);
        exit;
    }
}
