<?php
ob_start();
if (session_status() === PHP_SESSION_NONE) session_start();

header('Content-Type: application/json; charset=utf-8');
ini_set('display_errors', 0);
error_reporting(0);

require_once realpath(dirname(__DIR__, 3) . '/services/Model.php');
$obj = new Model();

$user_id = $_SESSION['userid'] ?? 0;
$table   = 're_tbl_zone';

function json_out($arr, $code = 200)
{
    http_response_code($code);
    if (ob_get_length()) ob_clean();
    echo json_encode($arr, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

if ($user_id <= 0) {
    json_out(['ok' => false, 'msg' => 'Unauthorized (session expired)'], 401);
}

$action = $_GET['action'] ?? 'list';

$has_reseller_id = false;
try {
    $cols = $obj->raw_sql("SHOW COLUMNS FROM `$table` LIKE 'reseller_id'");
    $has_reseller_id = !empty($cols);
} catch (Throwable $e) {
    $has_reseller_id = false;
}

$ownerCol = $has_reseller_id ? 'reseller_id' : 'created_by'; // fallback
$ownerWhere = "$ownerCol = $user_id";

/* -------- DataTable LIST -------- */
if ($action === 'list') {

    $draw   = (int)($_GET['draw'] ?? 1);
    $start  = (int)($_GET['start'] ?? 0);
    $length = (int)($_GET['length'] ?? 10);
    $search = trim($_GET['search']['value'] ?? '');

    $orderColIndex = (int)($_GET['order'][0]['column'] ?? 0);
    $orderDir      = (strtolower($_GET['order'][0]['dir'] ?? 'desc') === 'asc') ? 'ASC' : 'DESC';

    $columns = [
        0 => 'zone_id',
        1 => 'zone_name',
        2 => 'created_by',
    ];
    $orderBy = $columns[$orderColIndex] ?? 'zone_id';

    $where = $ownerWhere;
    if ($search !== '') {
        $s = addslashes($search);
        $where .= " AND (zone_name LIKE '%$s%' OR zone_id LIKE '%$s%')";
    }

    $totalRow = $obj->raw_sql("SELECT COUNT(*) AS total FROM `$table` WHERE $ownerWhere");
    $recordsTotal = (int)($totalRow[0]['total'] ?? 0);

    $filteredRow = $obj->raw_sql("SELECT COUNT(*) AS total FROM `$table` WHERE $where");
    $recordsFiltered = (int)($filteredRow[0]['total'] ?? 0);

    $rows = $obj->raw_sql("
        SELECT 
            z.zone_id,
            z.zone_name,
            u.FullName AS created_by_name,
            u.UserId   AS created_by_id
        FROM `$table` AS z
        LEFT JOIN `_reseller_createuser` AS u
            ON u.UserId = z.created_by
        WHERE $where
        ORDER BY $orderBy $orderDir
        LIMIT $start, $length
    ");


    $data = [];
    foreach ($rows as $r) {
        $data[] = [
            'zone_id'    => (int)$r['zone_id'],
            'zone_name'  => $r['zone_name'],
            'created_by' => $r['created_by_name'],
            'action'     => '<button type="button" class="btn btn-sm btn-outline-primary editZone"
                            data-id="' . (int)$r['zone_id'] . '"
                            data-name="' . htmlspecialchars($r['zone_name'], ENT_QUOTES) . '">
                            <i class="fa-solid fa-pen-to-square me-1"></i>Edit</button>

                            <button type="button" id="deleteZone" class="btn btn-sm btn-danger"
                            data-id="' . (int)$r['zone_id'] . '"
                            data-name="' . htmlspecialchars($r['zone_name'], ENT_QUOTES) . '">
                            <i class="fa-solid fa-trash-can me-1"></i>Delete</button>',
        ];
    }

    json_out([
        "draw"            => $draw,
        "recordsTotal"    => $recordsTotal,
        "recordsFiltered" => $recordsFiltered,
        "data"            => $data
    ]);
}

/* -------- ADD -------- */
if ($action === 'add') {
    $zone_name = trim($_POST['zone_name'] ?? '');
    if ($zone_name === '') json_out(['ok' => false, 'msg' => 'Zone name required'], 400);

    // duplicate per reseller/user
    $dup = $obj->raw_sql("SELECT zone_id FROM `$table`
                          WHERE $ownerWhere AND zone_name='" . addslashes($zone_name) . "'
                          LIMIT 1");
    if (!empty($dup)) json_out(['ok' => false, 'msg' => 'This zone already exists'], 409);

    $payload = [
        'zone_name'  => $zone_name,
        'created_by' => $user_id,
    ];
    if ($has_reseller_id) $payload['reseller_id'] = $user_id;

    $newId = $obj->Insert_data($table, $payload);

    json_out(['ok' => true, 'msg' => 'Zone added', 'id' => $newId]);
}

/* -------- UPDATE -------- */
if ($action === 'update') {
    $zone_id   = (int)($_POST['zone_id'] ?? 0);
    $zone_name = trim($_POST['zone_name'] ?? '');

    if ($zone_id <= 0) json_out(['ok' => false, 'msg' => 'Invalid zone id'], 400);
    if ($zone_name === '') json_out(['ok' => false, 'msg' => 'Zone name required'], 400);

    $own = $obj->raw_sql("SELECT zone_id FROM `$table` WHERE zone_id=$zone_id AND $ownerWhere LIMIT 1");
    if (empty($own)) json_out(['ok' => false, 'msg' => 'Unauthorized'], 403);

    $dup = $obj->raw_sql("SELECT zone_id FROM `$table`
                          WHERE $ownerWhere AND zone_name='" . addslashes($zone_name) . "'
                            AND zone_id<>$zone_id
                          LIMIT 1");
    if (!empty($dup)) json_out(['ok' => false, 'msg' => 'This zone already exists'], 409);

    $obj->Update_data($table, ['zone_name' => $zone_name], "zone_id='$zone_id'");

    json_out(['ok' => true, 'msg' => 'Zone updated']);
}

json_out(['ok' => false, 'msg' => 'Invalid action'], 400);
