<?php

// No namespace – keep consistent with BaseController and manual loading

class FormsController extends BaseController
{
    /**
     * @var PDO
     */
    private $pdo;

    /**
     * @var FormBuilderService
     */
    private $formService;

    /**
     * Accept $pdo for compatibility with routes that do:
     * new FormsController($pdo)
     */
    public function __construct($pdo = null)
    {
        parent::__construct();

        $this->pdo = $pdo ?: Database::getConnection();
        $this->formService = new FormBuilderService();
    }

    // ==================== APP PAGES (AUTH REQUIRED) ====================

    /**
     * Forms listing (SkyBlue index)
     */
    public function index()
    {
        $this->authCheck();

        $tenantId = $_SESSION['tenant_id'];

        try {
            // List forms with submission stats
            $stmt = $this->pdo->prepare("
                SELECT 
                    f.*,
                    COUNT(fs.id)       AS submissions_count,
                    MAX(fs.created_at) AS last_submission_at
                FROM forms f
                LEFT JOIN form_submissions fs 
                    ON fs.form_id = f.id
                WHERE f.tenant_id = ?
                GROUP BY f.id
                ORDER BY f.created_at DESC
            ");
            $stmt->execute([$tenantId]);
            $forms = $stmt->fetchAll(PDO::FETCH_ASSOC);
        } catch (Exception $e) {
            error_log('Forms index error: ' . $e->getMessage());
            $forms = [];
        }

        // SkyBlue forms index view
        $this->render('pages/forms/index', [
            'forms'       => $forms,
            'currentPage' => 'forms',
            'pageTitle'   => 'Forms',
        ]);
    }

    /**
     * Create form (SkyBlue builder)
     * - GET: show builder
     * - POST: save new form
     */
    public function create()
    {
        if (!Auth::check()) {
            header('Location: /lead-management/public/login');
            exit;
        }

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $this->handleFormCreate();
            return;
        }

        $this->render('pages/forms/builder', [
            'form'             => null,
            'fieldTypes'       => $this->formService->getFieldTypes(),
            'defaultStructure' => $this->getDefaultFormStructure(),
            'currentPage'      => 'forms',
            'pageTitle'        => 'Create Form',
        ]);
    }

    public function edit($formId)
    {
        if (!Auth::check()) {
            header('Location: /lead-management/public/login');
            exit;
        }

        $form = $this->getForm($formId);
        if (!$form) {
            $_SESSION['error'] = 'Form not found';
            header('Location: /lead-management/public/app/forms');
            exit;
        }

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $this->handleFormUpdate($formId);
            return;
        }

        $structure = json_decode($form['structure'] ?? '{}', true);

        $this->render('pages/forms/builder', [
            'form'             => $form,
            'fieldTypes'       => $this->formService->getFieldTypes(),
            'defaultStructure' => $structure ?: $this->getDefaultFormStructure(),
            'currentPage'      => 'forms',
            'pageTitle'        => 'Edit Form',
        ]);
    }

    /**
     * Form submissions list (SkyBlue submissions page)
     */
    public function submissions($formId)
    {
        $this->authCheck();

        $form = $this->getForm($formId);
        if (!$form) {
            $_SESSION['error'] = 'Form not found';
            header('Location: /lead-management/public/app/forms');
            exit;
        }

        $tenantId = $_SESSION['tenant_id'];
        $page     = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
        $limit    = 20;
        $offset   = ($page - 1) * $limit;

        try {
            // Submissions
            $stmt = $this->pdo->prepare("
                SELECT 
                    fs.*,
                    l.first_name,
                    l.last_name,
                    l.email 
                FROM form_submissions fs 
                LEFT JOIN leads l ON fs.lead_id = l.id 
                WHERE fs.form_id = ? AND fs.tenant_id = ? 
                ORDER BY fs.created_at DESC 
                LIMIT ? OFFSET ?
            ");
            $stmt->bindValue(1, $formId, PDO::PARAM_INT);
            $stmt->bindValue(2, $tenantId, PDO::PARAM_INT);
            $stmt->bindValue(3, $limit, PDO::PARAM_INT);
            $stmt->bindValue(4, $offset, PDO::PARAM_INT);
            $stmt->execute();
            $submissions = $stmt->fetchAll(PDO::FETCH_ASSOC);

            // Total count
            $countStmt = $this->pdo->prepare("
                SELECT COUNT(*) as total 
                FROM form_submissions 
                WHERE form_id = ? AND tenant_id = ?
            ");
            $countStmt->execute([$formId, $tenantId]);
            $totalRow = $countStmt->fetch(PDO::FETCH_ASSOC);
            $total    = $totalRow ? (int)$totalRow['total'] : 0;
        } catch (Exception $e) {
            error_log('Form submissions error: ' . $e->getMessage());
            $submissions = [];
            $total       = 0;
        }

        $this->render('pages/forms/submissions', [
            'form'        => $form,
            'submissions' => $submissions,
            'pagination'  => [
                'page'  => $page,
                'limit' => $limit,
                'total' => $total,
                'pages' => $limit > 0 ? (int)ceil($total / $limit) : 1,
            ],
            'currentPage' => 'forms',
            'pageTitle'   => 'Form Submissions',
        ]);
    }

    /**
     * Form analytics (SkyBlue analytics page)
     */
    public function analytics($formId)
    {
        $this->authCheck();

        $form = $this->getForm($formId);
        if (!$form) {
            $_SESSION['error'] = 'Form not found';
            header('Location: /lead-management/public/app/forms');
            exit;
        }

        $tenantId = $_SESSION['tenant_id'];

        // Aggregate analytics
        $stmt = $this->pdo->prepare("
            SELECT 
                COUNT(*)                                   AS total_submissions,
                COUNT(DISTINCT DATE(created_at))           AS active_days,
                AVG(ai_score)                              AS avg_ai_score,
                MIN(created_at)                            AS first_submission,
                MAX(created_at)                            AS last_submission,
                COUNT(CASE WHEN lead_id IS NOT NULL THEN 1 END) AS leads_created
            FROM form_submissions 
            WHERE form_id = ? AND tenant_id = ?
        ");
        $stmt->execute([$formId, $tenantId]);
        $analytics = $stmt->fetch(PDO::FETCH_ASSOC) ?: [];

        // Submission trends (last 30 days)
        $stmt = $this->pdo->prepare("
            SELECT 
                DATE(created_at) AS date,
                COUNT(*)         AS submissions
            FROM form_submissions 
            WHERE form_id = ? 
              AND tenant_id = ? 
              AND created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)
            GROUP BY DATE(created_at)
            ORDER BY date ASC
        ");
        $stmt->execute([$formId, $tenantId]);
        $trends = $stmt->fetchAll(PDO::FETCH_ASSOC);

        // Fill missing dates for smooth chart
        $filledTrends = [];
        $currentDate  = date('Y-m-d', strtotime('-29 days'));
        $endDate      = date('Y-m-d');

        while ($currentDate <= $endDate) {
            $found = false;
            foreach ($trends as $trend) {
                if ($trend['date'] === $currentDate) {
                    $filledTrends[] = $trend;
                    $found          = true;
                    break;
                }
            }
            if (!$found) {
                $filledTrends[] = ['date' => $currentDate, 'submissions' => 0];
            }
            $currentDate = date('Y-m-d', strtotime($currentDate . ' +1 day'));
        }

        // Lead conversion analytics
        $stmt = $this->pdo->prepare("
            SELECT 
                COUNT(DISTINCT fs.lead_id)                                           AS total_leads,
                COUNT(DISTINCT CASE WHEN l.status = 'converted' THEN l.id END)       AS converted_leads,
                COUNT(DISTINCT CASE WHEN l.status = 'qualified' THEN l.id END)       AS qualified_leads,
                AVG(l.ai_score)                                                      AS avg_lead_score
            FROM form_submissions fs
            LEFT JOIN leads l ON fs.lead_id = l.id
            WHERE fs.form_id = ? AND fs.tenant_id = ?
        ");
        $stmt->execute([$formId, $tenantId]);
        $conversion = $stmt->fetch(PDO::FETCH_ASSOC) ?: [];

        // Simple completion proxy (size of submission data)
        $stmt = $this->pdo->prepare("
            SELECT 
                COUNT(*)                              AS total_submissions,
                AVG(LENGTH(submission_data))          AS avg_data_length
            FROM form_submissions 
            WHERE form_id = ? AND tenant_id = ?
        ");
        $stmt->execute([$formId, $tenantId]);
        $completion = $stmt->fetch(PDO::FETCH_ASSOC) ?: [];

        $this->render('pages/forms/analytics', [
            'form'        => $form,
            'analytics'   => $analytics,
            'trends'      => $filledTrends,
            'conversion'  => $conversion,
            'completion'  => $completion,
            'currentPage' => 'forms',
            'pageTitle'   => 'Form Analytics',
        ]);
    }

    /**
     * Update form status (draft/active/archived)
     */
    public function updateStatus($formId)
    {
        $this->authCheck();

        $status = $_POST['status'] ?? '';
        if (!in_array($status, ['draft', 'active', 'archived'], true)) {
            $_SESSION['error'] = 'Invalid status';
            header('Location: /lead-management/public/app/forms');
            exit;
        }

        $tenantId = $_SESSION['tenant_id'];

        $stmt = $this->pdo->prepare("
            UPDATE forms 
            SET status = ? 
            WHERE id = ? AND tenant_id = ?
        ");
        $stmt->execute([$status, $formId, $tenantId]);

        $_SESSION['success'] = "Form status updated to {$status}";
        header('Location: /lead-management/public/app/forms');
        exit;
    }

    /**
     * Delete a form
     */
    public function delete($formId)
    {
        $this->authCheck();

        $tenantId = $_SESSION['tenant_id'];

        $stmt = $this->pdo->prepare("
            DELETE FROM forms 
            WHERE id = ? AND tenant_id = ?
        ");
        $stmt->execute([$formId, $tenantId]);

        $_SESSION['success'] = 'Form deleted successfully';
        header('Location: /lead-management/public/app/forms');
        exit;
    }

    // ==================== PUBLIC FORM ROUTES (NO AUTH) ====================

    /**
     * Public embed view
     */
    public function embed($formId)
    {
        $form = $this->getForm($formId, false); // no tenant check for public
        if (!$form || ($form['status'] ?? 'draft') !== 'active') {
            http_response_code(404);
            echo 'Form not found';
            exit;
        }

        $structure = json_decode($form['structure'] ?? '{}', true);
        $settings  = json_decode($form['settings'] ?? '{}', true);

        header('Content-Type: text/html; charset=utf-8');
        echo $this->renderEmbeddedForm($structure, $settings, $formId);
        exit;
    }

    /**
     * Public submit endpoint
     */
    public function submit($formId)
    {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            http_response_code(405);
            echo json_encode(['success' => false, 'error' => 'Method not allowed']);
            exit;
        }

        $form = $this->getForm($formId, false); // no tenant check for public
        if (!$form || ($form['status'] ?? 'draft') !== 'active') {
            http_response_code(404);
            echo json_encode(['success' => false, 'error' => 'Form not found']);
            exit;
        }

        try {
            $structure      = json_decode($form['structure'] ?? '{}', true);
            $settings       = json_decode($form['settings'] ?? '{}', true);
            $submissionData = $_POST;

            // Validate required fields
            $errors = $this->validateFormSubmission($structure, $submissionData);
            if (!empty($errors)) {
                if ($this->isAjaxRequest()) {
                    header('Content-Type: application/json');
                    echo json_encode(['success' => false, 'errors' => $errors]);
                    exit;
                }
                $_SESSION['form_error'] = implode(', ', $errors);
                header('Location: ' . ($_SERVER['HTTP_REFERER'] ?? '/'));
                exit;
            }

            $this->pdo->beginTransaction();

            // Store submission
            $stmt = $this->pdo->prepare("
                INSERT INTO form_submissions (form_id, tenant_id, submission_data, ip_address, user_agent)
                VALUES (?, ?, ?, ?, ?)
            ");
            $stmt->execute([
                $formId,
                $form['tenant_id'],
                json_encode($submissionData),
                $_SERVER['REMOTE_ADDR']      ?? 'unknown',
                $_SERVER['HTTP_USER_AGENT']  ?? 'unknown',
            ]);

            $submissionId = $this->pdo->lastInsertId();
            $leadId       = null;

            // Create lead if enabled
            $autoCreate = $settings['auto_create_lead'] ?? true;
            if ($autoCreate) {
                $leadId = $this->createLeadFromSubmission($form, $submissionData, $submissionId);

                // Simple auto-score if enabled
                if ($leadId && ($settings['auto_ai_scoring'] ?? false)) {
                    $this->autoScoreLead($leadId, $submissionData);
                }
            }

            $this->pdo->commit();

            $response = [
                'success'       => true,
                'message'       => $settings['success_message'] ?? 'Thank you for your submission!',
                'submission_id' => $submissionId,
                'lead_created'  => !is_null($leadId),
            ];

            if ($this->isAjaxRequest()) {
                header('Content-Type: application/json');
                echo json_encode($response);
                exit;
            }

            $_SESSION['form_success'] = $response['message'];
            header('Location: ' . ($_SERVER['HTTP_REFERER'] ?? '/'));
            exit;
        } catch (Exception $e) {
            if ($this->pdo->inTransaction()) {
                $this->pdo->rollBack();
            }
            error_log("Form submission error: " . $e->getMessage());

            $errorResponse = ['success' => false, 'error' => 'Submission failed'];

            if ($this->isAjaxRequest()) {
                header('Content-Type: application/json');
                echo json_encode($errorResponse);
                exit;
            }

            $_SESSION['form_error'] = $errorResponse['error'];
            header('Location: ' . ($_SERVER['HTTP_REFERER'] ?? '/'));
            exit;
        }
    }

    // ==================== PRIVATE HELPERS ====================

    private function handleFormCreate()
    {
        $tenantId    = $_SESSION['tenant_id'];
        $name        = $_POST['name']        ?? '';
        $description = $_POST['description'] ?? '';
        $structure   = json_decode($_POST['structure'] ?? '{}', true);
        $settings    = json_decode($_POST['settings'] ?? '{}', true);

        if (empty($name)) {
            $_SESSION['error'] = 'Form name is required';
            header('Location: /lead-management/public/app/forms/create');
            exit;
        }

        $validation = $this->formService->validateFormStructure($structure);
        if (!$validation['valid']) {
            $_SESSION['error'] = $validation['error'];
            header('Location: /lead-management/public/app/forms/create');
            exit;
        }

        // Insert WITHOUT user_id (column doesn't exist in your schema)
        $stmt = $this->pdo->prepare("
            INSERT INTO forms (tenant_id, name, description, structure, settings, embed_code)
            VALUES (?, ?, ?, ?, ?, ?)
        ");

        // Temporary embed code (will update with real ID)
        $embedCodePlaceholder = $this->formService->generateEmbedCode(0, $settings);

        $stmt->execute([
            $tenantId,
            $name,
            $description,
            json_encode($structure),
            json_encode($settings),
            $embedCodePlaceholder,
        ]);

        $formId = $this->pdo->lastInsertId();

        // Update embed code with actual form ID
        $embedCode = $this->formService->generateEmbedCode($formId, $settings);
        $update    = $this->pdo->prepare("UPDATE forms SET embed_code = ? WHERE id = ?");
        $update->execute([$embedCode, $formId]);

        $_SESSION['success'] = 'Form created successfully';
        header('Location: /lead-management/public/app/forms/' . $formId . '/edit');
        exit;
    }

    private function handleFormUpdate($formId)
    {
        $tenantId    = $_SESSION['tenant_id'];
        $name        = $_POST['name']        ?? '';
        $description = $_POST['description'] ?? '';
        $structure   = json_decode($_POST['structure'] ?? '{}', true);
        $settings    = json_decode($_POST['settings'] ?? '{}', true);

        if (empty($name)) {
            $_SESSION['error'] = 'Form name is required';
            header('Location: /lead-management/public/app/forms/' . $formId . '/edit');
            exit;
        }

        $validation = $this->formService->validateFormStructure($structure);
        if (!$validation['valid']) {
            $_SESSION['error'] = $validation['error'];
            header('Location: /lead-management/public/app/forms/' . $formId . '/edit');
            exit;
        }

        $embedCode = $this->formService->generateEmbedCode($formId, $settings);

        $stmt = $this->pdo->prepare("
            UPDATE forms 
            SET name = ?, description = ?, structure = ?, settings = ?, embed_code = ?
            WHERE id = ? AND tenant_id = ?
        ");

        $stmt->execute([
            $name,
            $description,
            json_encode($structure),
            json_encode($settings),
            $embedCode,
            $formId,
            $tenantId,
        ]);

        $_SESSION['success'] = 'Form updated successfully';
        header('Location: /lead-management/public/app/forms/' . $formId . '/edit');
        exit;
    }

    private function validateFormSubmission($structure, $data)
    {
        $errors = [];

        foreach ($structure['fields'] ?? [] as $field) {
            $fieldId  = $field['id']          ?? null;
            $label    = $field['label']       ?? 'Field';
            $required = $field['required']    ?? false;
            $type     = $field['type']        ?? 'text';

            if ($required && $fieldId && empty($data[$fieldId])) {
                $errors[] = "{$label} is required";
            }

            if (
                $type === 'email' && $fieldId && !empty($data[$fieldId]) &&
                !filter_var($data[$fieldId], FILTER_VALIDATE_EMAIL)
            ) {
                $errors[] = "{$label} must be a valid email address";
            }
        }

        return $errors;
    }

    private function createLeadFromSubmission($form, $submissionData, $submissionId)
    {
        // Map common fields
        $firstName = $submissionData['first_name'] ?? ($submissionData['name'] ?? 'Unknown');
        $lastName  = $submissionData['last_name'] ?? '';
        $email     = $submissionData['email'] ?? '';
        $phone     = $submissionData['phone'] ?? ($submissionData['telephone'] ?? '');
        $company   = $submissionData['company'] ?? ($submissionData['business'] ?? '');

        $stmt = $this->pdo->prepare("
            INSERT INTO leads (
                tenant_id, form_id, submission_id,
                first_name, last_name, email, phone, company,
                source, status, notes
            )
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        ");

        $stmt->execute([
            $form['tenant_id'],
            $form['id'],
            $submissionId,
            $firstName,
            $lastName,
            $email,
            $phone,
            $company,
            'form_' . $form['id'],
            'new',
            'Created from form submission: ' . json_encode($submissionData),
        ]);

        $leadId = $this->pdo->lastInsertId();

        // link submission back to lead
        $update = $this->pdo->prepare("
            UPDATE form_submissions 
            SET lead_id = ? 
            WHERE id = ?
        ");
        $update->execute([$leadId, $submissionId]);

        return $leadId;
    }

    private function autoScoreLead($leadId, $submissionData)
    {
        // Simple heuristic scoring (can be replaced with AIService later)
        $score = 50;

        if (!empty($submissionData['company']))   $score += 10;
        if (!empty($submissionData['phone']))     $score += 10;
        if (!empty($submissionData['budget']))    $score += 15;
        if (!empty($submissionData['timeframe']) && $submissionData['timeframe'] === 'immediate') {
            $score += 15;
        }

        $category = $score >= 80 ? 'Hot' : ($score >= 60 ? 'Warm' : 'Cold');

        $stmt = $this->pdo->prepare("
            UPDATE leads 
            SET ai_score = ?, ai_score_category = ?, ai_score_reasoning = ?, last_ai_scoring = NOW()
            WHERE id = ?
        ");
        $stmt->execute([
            $score,
            $category,
            'Auto-scored based on form submission data',
            $leadId,
        ]);
    }

    /**
     * Get a form by ID
     *
     * @param int  $formId
     * @param bool $checkTenant
     */
    private function getForm($formId, $checkTenant = true)
    {
        if ($checkTenant && !empty($_SESSION['tenant_id'])) {
            $stmt = $this->pdo->prepare("
                SELECT * 
                FROM forms 
                WHERE id = ? AND tenant_id = ?
            ");
            $stmt->execute([$formId, $_SESSION['tenant_id']]);
        } else {
            $stmt = $this->pdo->prepare("
                SELECT * 
                FROM forms 
                WHERE id = ?
            ");
            $stmt->execute([$formId]);
        }

        return $stmt->fetch(PDO::FETCH_ASSOC);
    }

    private function getDefaultFormStructure()
    {
        return [
            'fields' => [
                [
                    'id'          => 'first_name',
                    'type'        => 'text',
                    'label'       => 'First Name',
                    'required'    => true,
                    'placeholder' => 'Enter your first name',
                ],
                [
                    'id'          => 'last_name',
                    'type'        => 'text',
                    'label'       => 'Last Name',
                    'required'    => true,
                    'placeholder' => 'Enter your last name',
                ],
                [
                    'id'          => 'email',
                    'type'        => 'email',
                    'label'       => 'Email Address',
                    'required'    => true,
                    'placeholder' => 'Enter your email',
                ],
            ],
            'settings' => [
                'submit_text'      => 'Submit',
                'success_message'  => 'Thank you for your submission!',
                'auto_create_lead' => true,
                'auto_ai_scoring'  => true,
            ],
            'version' => '1.0',
        ];
    }

    private function renderEmbeddedForm($structure, $settings, $formId)
    {
        $html  = '<!DOCTYPE html>';
        $html .= '<html lang="en">';
        $html .= '<head>';
        $html .= '<meta charset="UTF-8">';
        $html .= '<meta name="viewport" content="width=device-width, initial-scale=1.0">';
        $html .= '<title>Form</title>';
        $html .= '<script src="https://cdn.tailwindcss.com"></script>';
        $html .= '<style>';
        $html .= 'body { font-family: system-ui, sans-serif; margin: 0; padding: 20px; }';
        $html .= '.form-success { background: #d4edda; color: #155724; padding: 12px; border-radius: 4px; margin-bottom: 16px; }';
        $html .= '.form-error { background: #f8d7da; color: #721c24; padding: 12px; border-radius: 4px; margin-bottom: 16px; }';
        $html .= '</style>';
        $html .= '</head>';
        $html .= '<body class="bg-gray-50">';

        $html .= '<div class="max-w-md mx-auto bg-white rounded-lg shadow-md p-6">';

        if (!empty($_SESSION['form_success'])) {
            $html .= '<div class="form-success">' . htmlspecialchars($_SESSION['form_success']) . '</div>';
            unset($_SESSION['form_success']);
        } elseif (!empty($_SESSION['form_error'])) {
            $html .= '<div class="form-error">' . htmlspecialchars($_SESSION['form_error']) . '</div>';
            unset($_SESSION['form_error']);
        }

        $html .= '<h2 class="text-xl font-semibold text-gray-800 mb-4">' . htmlspecialchars($settings['title'] ?? 'Contact Form') . '</h2>';

        if (!empty($settings['description'])) {
            $html .= '<p class="text-gray-600 mb-6">' . htmlspecialchars($settings['description']) . '</p>';
        }

        $html .= $this->formService->renderForm($structure);
        $html .= '</div>';

        $html .= '<script>';
        $html .= 'document.getElementById("leadintelligence-form").addEventListener("submit", function(e) {';
        $html .= '    e.preventDefault();';
        $html .= '    var form = this;';
        $html .= '    var formData = new FormData(form);';
        $html .= '    fetch("/lead-management/public/forms/' . $formId . '/submit", {';
        $html .= '        method: "POST",';
        $html .= '        body: formData';
        $html .= '    })';
        $html .= '    .then(response => response.json())';
        $html .= '    .then(function(data) {';
        $html .= '        if (data.success) {';
        $html .= '            form.innerHTML = \'<div class="form-success">\' + data.message + \'</div>\';';
        $html .= '            window.parent.postMessage({';
        $html .= '                type: "leadintelligence-form-height",';
        $html .= '                height: document.body.scrollHeight';
        $html .= '            }, "*");';
        $html .= '        } else {';
        $html .= '            alert("Error: " + (data.error || "Unknown error"));';
        $html .= '        }';
        $html .= '    })';
        $html .= '    .catch(function(error) {';
        $html .= '        alert("Submission error: " + error);';
        $html .= '    });';
        $html .= '});';
        $html .= '</script>';

        $html .= '</body>';
        $html .= '</html>';

        return $html;
    }

    private function isAjaxRequest()
    {
        return !empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
            strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest';
    }
}
