<?php

class LandingController {
    private $funnelModel;

    public function __construct() {
        $this->funnelModel = new FunnelModel();
    }

    public function builder($funnelId, $pageId) {
        $funnel = $this->funnelModel->getById($funnelId);
        $page = $this->funnelModel->getPageById($pageId);

        if (!$funnel || !$page || $page['funnel_id'] != $funnelId) {
            redirect('/funnels');
        }

        $formModel = new FormModel();
        $forms = $formModel->getAll();

        require_once APP_PATH . '/views/landing/builder.php';
    }

    public function save() {
        $data = json_decode(file_get_contents('php://input'), true);
        $pageId  = (int)($data['page_id'] ?? 0);
        $content = $data['content'] ?? '';

        if (!$pageId) {
            jsonResponse(['success' => false, 'message' => 'Page ID required.'], 400);
        }

        $page = $this->funnelModel->getPageById($pageId);
        if (!$page) {
            jsonResponse(['success' => false, 'message' => 'Page not found.'], 404);
        }

        // content is JSON of sections
        $this->funnelModel->updatePage($pageId, [
            'title'     => $page['title'],
            'content'   => is_array($content) ? json_encode($content) : $content,
            'form_id'   => $page['form_id'],
            'page_type' => $page['page_type'],
            'settings'  => $page['settings'],
        ]);

        jsonResponse(['success' => true, 'message' => 'Page saved!']);
    }

    public function uploadImage() {
        $result = handleFileUpload('image', ['jpg', 'jpeg', 'png', 'gif', 'webp']);
        if ($result['success']) {
            jsonResponse([
                'success'  => true,
                'filename' => $result['filename'],
                'url'      => uploadUrl($result['filename']),
            ]);
        } else {
            jsonResponse(['success' => false, 'message' => $result['message']], 400);
        }
    }
}
