<?php

class FunnelController {
    private $funnelModel;

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

    public function index() {
        $funnels = $this->funnelModel->getAll();
        require_once APP_PATH . '/views/funnels/index.php';
    }

    public function create() {
        require_once APP_PATH . '/views/funnels/create.php';
    }

    public function store() {
        $name = sanitize($_POST['name'] ?? '');
        if (empty($name)) {
            $_SESSION['error'] = 'Funnel name is required.';
            redirect('/funnels/create');
        }

        $slug = generateSlug($name);
        $id = $this->funnelModel->create([
            'name'        => $name,
            'description' => sanitize($_POST['description'] ?? ''),
            'slug'        => $slug,
        ]);

        $_SESSION['success'] = 'Funnel created!';
        redirect('/funnels/' . $id . '/edit');
    }

    public function edit($id) {
        $funnel = $this->funnelModel->getById($id);
        if (!$funnel) { redirect('/funnels'); }

        $pages = $this->funnelModel->getPagesById($id);
        $formModel = new FormModel();
        $forms = $formModel->getAll();

        require_once APP_PATH . '/views/funnels/edit.php';
    }

    public function update($id) {
        $funnel = $this->funnelModel->getById($id);
        if (!$funnel) {
            jsonResponse(['success' => false, 'message' => 'Funnel not found.']);
        }

        $name = sanitize($_POST['name'] ?? '');
        if (empty($name)) {
            jsonResponse(['success' => false, 'message' => 'Name required.']);
        }

        $this->funnelModel->update($id, [
            'name'        => $name,
            'description' => sanitize($_POST['description'] ?? ''),
        ]);

        jsonResponse(['success' => true, 'message' => 'Funnel updated!']);
    }

    public function delete($id) {
        $this->funnelModel->delete($id);
        jsonResponse(['success' => true, 'message' => 'Funnel deleted.']);
    }

    public function storePage() {
        $data = json_decode(file_get_contents('php://input'), true) ?? $_POST;
        $funnelId = (int)($data['funnel_id'] ?? 0);
        $title    = sanitize($data['title'] ?? '');

        if (!$funnelId || empty($title)) {
            jsonResponse(['success' => false, 'message' => 'Funnel ID and title required.'], 400);
        }

        $id = $this->funnelModel->createPage([
            'funnel_id' => $funnelId,
            'title'     => $title,
            'content'   => $data['content'] ?? '',
            'form_id'   => !empty($data['form_id']) ? (int)$data['form_id'] : null,
            'page_type' => sanitize($data['page_type'] ?? 'landing'),
            'settings'  => json_encode($data['settings'] ?? []),
        ]);

        $page = $this->funnelModel->getPageById($id);
        jsonResponse(['success' => true, 'page' => $page, 'message' => 'Page added!']);
    }

    public function updatePage($id) {
        $data = json_decode(file_get_contents('php://input'), true) ?? $_POST;
        $page = $this->funnelModel->getPageById($id);

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

        $this->funnelModel->updatePage($id, [
            'title'     => sanitize($data['title'] ?? $page['title']),
            'content'   => $data['content'] ?? '',
            'form_id'   => !empty($data['form_id']) ? (int)$data['form_id'] : null,
            'page_type' => sanitize($data['page_type'] ?? 'landing'),
            'settings'  => json_encode($data['settings'] ?? []),
        ]);

        $updated = $this->funnelModel->getPageById($id);
        jsonResponse(['success' => true, 'page' => $updated, 'message' => 'Page updated!']);
    }

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

    public function reorderPages() {
        $data = json_decode(file_get_contents('php://input'), true);
        $funnelId = (int)($data['funnel_id'] ?? 0);
        $order    = $data['order'] ?? [];

        if (!$funnelId || empty($order)) {
            jsonResponse(['success' => false, 'message' => 'Invalid data.'], 400);
        }

        $this->funnelModel->reorderPages($funnelId, $order);
        jsonResponse(['success' => true, 'message' => 'Pages reordered.']);
    }
}
