<?php

class PublicController {
    private $formModel;
    private $fieldModel;
    private $responseModel;
    private $funnelModel;

    public function __construct() {
        $this->formModel    = new FormModel();
        $this->fieldModel   = new FieldModel();
        $this->responseModel = new ResponseModel();
        $this->funnelModel  = new FunnelModel();
    }

    public function showForm($slug) {
        $form = $this->formModel->getBySlug($slug);
        if (!$form) {
            http_response_code(404);
            require_once APP_PATH . '/views/404.php';
            return;
        }
        $fields = $this->fieldModel->getByFormId($form['id']);
        require_once APP_PATH . '/views/public/form.php';
    }

    public function submitForm($slug) {
        $form = $this->formModel->getBySlug($slug);
        if (!$form) {
            jsonResponse(['success' => false, 'message' => 'Form not found.'], 404);
        }

        $fields = $this->fieldModel->getByFormId($form['id']);
        $errors = [];
        $values = [];

        foreach ($fields as $field) {
            $fieldName = 'field_' . $field['id'];

            if ($field['field_type'] === 'image' || $field['field_type'] === 'file') {
                if (isset($_FILES[$fieldName]) && $_FILES[$fieldName]['error'] === UPLOAD_ERR_OK) {
                    $allowedTypes = $field['field_type'] === 'image' ? ['jpg', 'jpeg', 'png', 'gif'] : ['jpg', 'jpeg', 'png', 'gif', 'pdf', 'doc', 'docx'];
                    $result = handleFileUpload($fieldName, $allowedTypes);
                    if ($result['success']) {
                        $values[$field['id']] = $result['filename'];
                    } else {
                        $errors[$field['id']] = $result['message'];
                    }
                } elseif ($field['required']) {
                    $errors[$field['id']] = $field['label'] . ' is required.';
                } else {
                    $values[$field['id']] = '';
                }
            } elseif ($field['field_type'] === 'checkbox') {
                $val = isset($_POST[$fieldName]) ? (is_array($_POST[$fieldName]) ? implode(', ', array_map('sanitize', $_POST[$fieldName])) : sanitize($_POST[$fieldName])) : '';
                if ($field['required'] && empty($val)) {
                    $errors[$field['id']] = $field['label'] . ' is required.';
                }
                $values[$field['id']] = $val;
            } else {
                $val = sanitize($_POST[$fieldName] ?? '');
                if ($field['required'] && empty($val)) {
                    $errors[$field['id']] = $field['label'] . ' is required.';
                }
                // Basic email validation
                if ($field['field_type'] === 'email' && !empty($val) && !filter_var($val, FILTER_VALIDATE_EMAIL)) {
                    $errors[$field['id']] = 'Please enter a valid email address.';
                }
                $values[$field['id']] = $val;
            }
        }

        if (!empty($errors)) {
            jsonResponse(['success' => false, 'errors' => $errors, 'message' => 'Please fix the errors below.'], 422);
        }

        // Save response
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'] ?? $_SERVER['REMOTE_ADDR'] ?? '';
        $ua = $_SERVER['HTTP_USER_AGENT'] ?? '';
        $responseId = $this->responseModel->create($form['id'], $ip, $ua);

        foreach ($values as $fieldId => $value) {
            $this->responseModel->addValue($responseId, $fieldId, $value);
        }

        // Build WhatsApp message
        $waMessage = "📋 *New Form Submission*\n";
        $waMessage .= "Form: " . $form['name'] . "\n";
        $waMessage .= "Date: " . date('d/m/Y H:i') . "\n\n";
        foreach ($fields as $field) {
            $val = $values[$field['id']] ?? '';
            if ($field['field_type'] === 'image' || $field['field_type'] === 'file') {
                $waMessage .= "*" . $field['label'] . ":* [File uploaded]\n";
            } else {
                $waMessage .= "*" . $field['label'] . ":* " . $val . "\n";
            }
        }

        $waUrl = '';
        if (!empty($form['whatsapp_number'])) {
            $phone = preg_replace('/[^0-9]/', '', $form['whatsapp_number']);
            $waUrl = 'https://wa.me/' . $phone . '?text=' . rawurlencode($waMessage);
        } else {
            $waUrl = 'https://wa.me/?text=' . rawurlencode($waMessage);
        }

        jsonResponse([
            'success'       => true,
            'message'       => $form['thank_you_message'] ?: 'Thank you for your submission!',
            'whatsapp_url'  => $waUrl,
            'redirect_url'  => $form['redirect_url'] ?? '',
            'response_id'   => $responseId,
        ]);
    }

    public function showFunnel($slug) {
        $funnel = $this->funnelModel->getBySlug($slug);
        if (!$funnel) {
            http_response_code(404);
            require_once APP_PATH . '/views/404.php';
            return;
        }

        $firstPage = $this->funnelModel->getFirstPage($funnel['id']);
        if (!$firstPage) {
            require_once APP_PATH . '/views/public/funnel_empty.php';
            return;
        }

        redirect('/funnel/' . $slug . '/page/' . $firstPage['id']);
    }

    public function showFunnelPage($slug, $pageId) {
        $funnel = $this->funnelModel->getBySlug($slug);
        if (!$funnel) {
            http_response_code(404);
            require_once APP_PATH . '/views/404.php';
            return;
        }

        $page = $this->funnelModel->getPageById($pageId);
        if (!$page || $page['funnel_id'] != $funnel['id']) {
            http_response_code(404);
            require_once APP_PATH . '/views/404.php';
            return;
        }

        $allPages = $this->funnelModel->getPagesById($funnel['id']);
        $currentIndex = 0;
        foreach ($allPages as $i => $p) {
            if ($p['id'] == $pageId) { $currentIndex = $i; break; }
        }
        $nextPage = $allPages[$currentIndex + 1] ?? null;
        $prevPage = $currentIndex > 0 ? $allPages[$currentIndex - 1] : null;

        // Load form if page has one
        $formFields = [];
        $form = null;
        if (!empty($page['form_id'])) {
            $form = $this->formModel->getById($page['form_id']);
            $formFields = $this->fieldModel->getByFormId($page['form_id']);
        }

        // Parse content sections
        $sections = [];
        if (!empty($page['content'])) {
            $decoded = json_decode($page['content'], true);
            $sections = is_array($decoded) ? $decoded : [];
        }

        require_once APP_PATH . '/views/public/funnel_page.php';
    }
}
