<?php

$uri = $requestUri;
$method = $_SERVER['REQUEST_METHOD'];

// ─── DASHBOARD ───────────────────────────────────────────
if ($uri === '/' || $uri === '') {
    require_once APP_PATH . '/controllers/DashboardController.php';
    $ctrl = new DashboardController();
    $ctrl->index();
    exit();
}

// ─── SETUP ───────────────────────────────────────────────
if ($uri === 'setup') {
    require_once APP_PATH . '/controllers/SetupController.php';
    $ctrl = new SetupController();
    $ctrl->index();
    exit();
}
if ($uri === 'setup/run' && $method === 'POST') {
    require_once APP_PATH . '/controllers/SetupController.php';
    $ctrl = new SetupController();
    $ctrl->run();
    exit();
}

// ─── FORMS ───────────────────────────────────────────────
if ($uri === 'forms') {
    require_once APP_PATH . '/controllers/FormController.php';
    $ctrl = new FormController();
    $ctrl->index();
    exit();
}
if ($uri === 'forms/create') {
    require_once APP_PATH . '/controllers/FormController.php';
    $ctrl = new FormController();
    $ctrl->create();
    exit();
}
if (preg_match('#^forms/(\d+)/edit$#', $uri, $m)) {
    require_once APP_PATH . '/controllers/FormController.php';
    $ctrl = new FormController();
    $ctrl->edit($m[1]);
    exit();
}
if (preg_match('#^forms/(\d+)/delete$#', $uri, $m) && $method === 'POST') {
    require_once APP_PATH . '/controllers/FormController.php';
    $ctrl = new FormController();
    $ctrl->delete($m[1]);
    exit();
}
if ($uri === 'forms/store' && $method === 'POST') {
    require_once APP_PATH . '/controllers/FormController.php';
    $ctrl = new FormController();
    $ctrl->store();
    exit();
}
if (preg_match('#^forms/(\d+)/update$#', $uri, $m) && $method === 'POST') {
    require_once APP_PATH . '/controllers/FormController.php';
    $ctrl = new FormController();
    $ctrl->update($m[1]);
    exit();
}

// ─── FIELDS (AJAX) ───────────────────────────────────────
if ($uri === 'fields/store' && $method === 'POST') {
    require_once APP_PATH . '/controllers/FieldController.php';
    $ctrl = new FieldController();
    $ctrl->store();
    exit();
}
if (preg_match('#^fields/(\d+)/update$#', $uri, $m) && $method === 'POST') {
    require_once APP_PATH . '/controllers/FieldController.php';
    $ctrl = new FieldController();
    $ctrl->update($m[1]);
    exit();
}
if (preg_match('#^fields/(\d+)/delete$#', $uri, $m) && $method === 'POST') {
    require_once APP_PATH . '/controllers/FieldController.php';
    $ctrl = new FieldController();
    $ctrl->delete($m[1]);
    exit();
}
if ($uri === 'fields/reorder' && $method === 'POST') {
    require_once APP_PATH . '/controllers/FieldController.php';
    $ctrl = new FieldController();
    $ctrl->reorder();
    exit();
}
if (preg_match('#^fields/(\d+)$#', $uri, $m)) {
    require_once APP_PATH . '/controllers/FieldController.php';
    $ctrl = new FieldController();
    $ctrl->get($m[1]);
    exit();
}

// ─── RESPONSES ───────────────────────────────────────────
if (preg_match('#^forms/(\d+)/responses$#', $uri, $m)) {
    require_once APP_PATH . '/controllers/ResponseController.php';
    $ctrl = new ResponseController();
    $ctrl->index($m[1]);
    exit();
}
if (preg_match('#^forms/(\d+)/responses/export$#', $uri, $m)) {
    require_once APP_PATH . '/controllers/ResponseController.php';
    $ctrl = new ResponseController();
    $ctrl->export($m[1]);
    exit();
}
if (preg_match('#^responses/(\d+)/delete$#', $uri, $m) && $method === 'POST') {
    require_once APP_PATH . '/controllers/ResponseController.php';
    $ctrl = new ResponseController();
    $ctrl->delete($m[1]);
    exit();
}

// ─── FUNNELS ─────────────────────────────────────────────
if ($uri === 'funnels') {
    require_once APP_PATH . '/controllers/FunnelController.php';
    $ctrl = new FunnelController();
    $ctrl->index();
    exit();
}
if ($uri === 'funnels/create') {
    require_once APP_PATH . '/controllers/FunnelController.php';
    $ctrl = new FunnelController();
    $ctrl->create();
    exit();
}
if ($uri === 'funnels/store' && $method === 'POST') {
    require_once APP_PATH . '/controllers/FunnelController.php';
    $ctrl = new FunnelController();
    $ctrl->store();
    exit();
}
if (preg_match('#^funnels/(\d+)/edit$#', $uri, $m)) {
    require_once APP_PATH . '/controllers/FunnelController.php';
    $ctrl = new FunnelController();
    $ctrl->edit($m[1]);
    exit();
}
if (preg_match('#^funnels/(\d+)/update$#', $uri, $m) && $method === 'POST') {
    require_once APP_PATH . '/controllers/FunnelController.php';
    $ctrl = new FunnelController();
    $ctrl->update($m[1]);
    exit();
}
if (preg_match('#^funnels/(\d+)/delete$#', $uri, $m) && $method === 'POST') {
    require_once APP_PATH . '/controllers/FunnelController.php';
    $ctrl = new FunnelController();
    $ctrl->delete($m[1]);
    exit();
}

// Funnel Pages
if ($uri === 'funnel-pages/store' && $method === 'POST') {
    require_once APP_PATH . '/controllers/FunnelController.php';
    $ctrl = new FunnelController();
    $ctrl->storePage();
    exit();
}
if (preg_match('#^funnel-pages/(\d+)/update$#', $uri, $m) && $method === 'POST') {
    require_once APP_PATH . '/controllers/FunnelController.php';
    $ctrl = new FunnelController();
    $ctrl->updatePage($m[1]);
    exit();
}
if (preg_match('#^funnel-pages/(\d+)/delete$#', $uri, $m) && $method === 'POST') {
    require_once APP_PATH . '/controllers/FunnelController.php';
    $ctrl = new FunnelController();
    $ctrl->deletePage($m[1]);
    exit();
}
if ($uri === 'funnel-pages/reorder' && $method === 'POST') {
    require_once APP_PATH . '/controllers/FunnelController.php';
    $ctrl = new FunnelController();
    $ctrl->reorderPages();
    exit();
}

// ─── LANDING BUILDER ─────────────────────────────────────
if (preg_match('#^funnels/(\d+)/pages/(\d+)/builder$#', $uri, $m)) {
    require_once APP_PATH . '/controllers/LandingController.php';
    $ctrl = new LandingController();
    $ctrl->builder($m[1], $m[2]);
    exit();
}
if ($uri === 'landing/save' && $method === 'POST') {
    require_once APP_PATH . '/controllers/LandingController.php';
    $ctrl = new LandingController();
    $ctrl->save();
    exit();
}
// Generic image upload (used by form builder image options)
if ($uri === 'upload/image' && $method === 'POST') {
    // Check for PHP upload errors first
    if (!isset($_FILES['image'])) {
        jsonResponse(['success' => false, 'message' => 'Tiada fail diterima. Semak php.ini upload_max_filesize & post_max_size.'], 400);
        exit();
    }
    $phpErrors = [
        UPLOAD_ERR_INI_SIZE   => 'Fail terlalu besar (upload_max_filesize dalam php.ini)',
        UPLOAD_ERR_FORM_SIZE  => 'Fail terlalu besar (MAX_FILE_SIZE form)',
        UPLOAD_ERR_PARTIAL    => 'Fail hanya diupload sebahagian',
        UPLOAD_ERR_NO_FILE    => 'Tiada fail dipilih',
        UPLOAD_ERR_NO_TMP_DIR => 'Folder tmp tidak wujud',
        UPLOAD_ERR_CANT_WRITE => 'Gagal tulis ke disk — semak permission folder',
        UPLOAD_ERR_EXTENSION  => 'Upload disekat oleh PHP extension',
    ];
    $errCode = $_FILES['image']['error'] ?? -1;
    if ($errCode !== UPLOAD_ERR_OK) {
        $msg = $phpErrors[$errCode] ?? 'PHP upload error code: ' . $errCode;
        jsonResponse(['success' => false, 'message' => $msg], 400);
        exit();
    }
    $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);
    }
    exit();
}
if ($uri === 'landing/upload-image' && $method === 'POST') {
    require_once APP_PATH . '/controllers/LandingController.php';
    $ctrl = new LandingController();
    $ctrl->uploadImage();
    exit();
}

// ─── PUBLIC ROUTES ───────────────────────────────────────
if (preg_match('#^form/([a-z0-9-]+)$#', $uri, $m)) {
    require_once APP_PATH . '/controllers/PublicController.php';
    $ctrl = new PublicController();
    $ctrl->showForm($m[1]);
    exit();
}
if (preg_match('#^form/([a-z0-9-]+)/submit$#', $uri, $m) && $method === 'POST') {
    require_once APP_PATH . '/controllers/PublicController.php';
    $ctrl = new PublicController();
    $ctrl->submitForm($m[1]);
    exit();
}
if (preg_match('#^funnel/([a-z0-9-]+)$#', $uri, $m)) {
    require_once APP_PATH . '/controllers/PublicController.php';
    $ctrl = new PublicController();
    $ctrl->showFunnel($m[1]);
    exit();
}
if (preg_match('#^funnel/([a-z0-9-]+)/page/(\d+)$#', $uri, $m)) {
    require_once APP_PATH . '/controllers/PublicController.php';
    $ctrl = new PublicController();
    $ctrl->showFunnelPage($m[1], $m[2]);
    exit();
}

// ─── 404 ─────────────────────────────────────────────────
http_response_code(404);
require_once APP_PATH . '/views/404.php';
