<?php
//Developer: core tech web designTechnology
//Whatsapp: +2349162671360
//Telegram: @jeditech

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

header('Content-Type: application/json');

$config_path = dirname(__DIR__, 2) . '/include/config.php';
if (file_exists($config_path)) {
    include($config_path);
} else {
    echo json_encode(['status' => '0', 'msg' => 'Configuration file not found']);
    exit();
}

// Verify admin
$stmt = $pdo->prepare("SELECT is_admin FROM users WHERE id = :user_id");
$stmt->bindParam(':user_id', $_SESSION['user_id'], PDO::PARAM_INT);
$stmt->execute();
$admin = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$admin || $admin['is_admin'] != 1) {
    echo json_encode(['status' => '0', 'msg' => 'Unauthorized access']);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['status' => '0', 'msg' => 'Invalid request method']);
    exit();
}

$action = isset($_POST['action']) ? trim($_POST['action']) : '';

// ── Helper: collect & validate service fields ──────────────────────────────────
function collectFields($post) {
    $jap_service_id = filter_var($post['jap_service_id'] ?? '', FILTER_VALIDATE_INT);
    $name           = isset($post['name'])     ? trim($post['name'])     : '';
    $category       = isset($post['category']) ? trim($post['category']) : '';
    $type           = isset($post['type'])      ? trim($post['type'])     : 'Default';
    $jap_rate       = filter_var($post['jap_rate']     ?? 0,       FILTER_VALIDATE_FLOAT);
    $our_rate       = filter_var($post['our_rate']     ?? '',       FILTER_VALIDATE_FLOAT);
    $min_quantity   = filter_var($post['min_quantity'] ?? 10,       FILTER_VALIDATE_INT);
    $max_quantity   = filter_var($post['max_quantity'] ?? 1000000,  FILTER_VALIDATE_INT);
    $refill         = isset($post['refill']) && in_array($post['refill'], ['0','1']) ? (int)$post['refill'] : 0;
    $cancel         = isset($post['cancel']) && in_array($post['cancel'], ['0','1']) ? (int)$post['cancel'] : 0;
    $status         = isset($post['status']) && in_array($post['status'], ['0','1']) ? (int)$post['status'] : 1;

    if (!$jap_service_id || empty($name) || empty($category) || $our_rate === false || $our_rate < 0) {
        return null;
    }
    if ($jap_rate === false) $jap_rate = 0;
    if (!$min_quantity || $min_quantity < 1) $min_quantity = 10;
    if (!$max_quantity || $max_quantity < 1) $max_quantity = 1000000;

    return compact('jap_service_id','name','category','type','jap_rate','our_rate',
                   'min_quantity','max_quantity','refill','cancel','status');
}

// ─── LIST — server-side DataTables ────────────────────────────────────────────
if ($action === 'list') {

    $draw   = (int)($_POST['draw']   ?? 1);
    $start  = (int)($_POST['start']  ?? 0);
    $length = (int)($_POST['length'] ?? 20);
    $length = max(1, min(100, $length));

    $search_val = trim($_POST['search_val'] ?? '');
    $f_status   = trim($_POST['f_status']   ?? 'all');
    $f_category = trim($_POST['f_category'] ?? 'all');

    // Safe column map for ordering
    $orderable_cols = [
        0  => 'id',
        1  => 'jap_service_id',
        2  => 'name',
        3  => 'category',
        4  => 'type',
        5  => 'jap_rate',
        6  => 'our_rate',
        7  => 'id',        // Min/Max — not meaningfully sortable, fall back to id
        8  => 'refill',
        9  => 'cancel',
        10 => 'status',
    ];
    $order_col_index = (int)($_POST['order'][0]['column'] ?? 0);
    $order_dir       = (isset($_POST['order'][0]['dir']) && strtoupper($_POST['order'][0]['dir']) === 'ASC') ? 'ASC' : 'DESC';
    $order_col       = $orderable_cols[$order_col_index] ?? 'id';

    // Build WHERE conditions and params as separate arrays
    // to avoid the named-param reuse issue between count + data queries
    $conditions = [];
    $bind_params = [];

    if ($f_status !== 'all' && $f_status !== '') {
        $conditions[]          = "status = :status";
        $bind_params['status'] = (int)$f_status;
    }
    if ($f_category !== 'all' && $f_category !== '') {
        $conditions[]            = "category = :category";
        $bind_params['category'] = $f_category;
    }
    if ($search_val !== '') {
        $conditions[]        = "(name LIKE :s1 OR category LIKE :s2 OR type LIKE :s3 OR jap_service_id LIKE :s4)";
        $bind_params['s1']   = "%{$search_val}%";
        $bind_params['s2']   = "%{$search_val}%";
        $bind_params['s3']   = "%{$search_val}%";
        $bind_params['s4']   = "%{$search_val}%";
    }

    $where_sql = $conditions ? ('WHERE ' . implode(' AND ', $conditions)) : '';

    try {
        // ── Total unfiltered count ────────────────────────────────────
        $recordsTotal = (int)$pdo->query("SELECT COUNT(*) FROM smm_services")->fetchColumn();

        // ── Filtered count ────────────────────────────────────────────
        $count_stmt = $pdo->prepare("SELECT COUNT(*) FROM smm_services $where_sql");
        foreach ($bind_params as $key => $val) {
            $count_stmt->bindValue(":$key", $val);
        }
        $count_stmt->execute();
        $recordsFiltered = (int)$count_stmt->fetchColumn();

        // ── Data rows ─────────────────────────────────────────────────
        $data_stmt = $pdo->prepare("
            SELECT *
            FROM smm_services
            $where_sql
            ORDER BY {$order_col} {$order_dir}
            LIMIT :lim OFFSET :off
        ");
        foreach ($bind_params as $key => $val) {
            $data_stmt->bindValue(":$key", $val);
        }
        $data_stmt->bindValue(':lim', $length, PDO::PARAM_INT);
        $data_stmt->bindValue(':off', $start,  PDO::PARAM_INT);
        $data_stmt->execute();
        $rows = $data_stmt->fetchAll(PDO::FETCH_ASSOC);

        // Add display row number
        foreach ($rows as $i => &$row) {
            $row['row_num'] = $start + $i + 1;
        }
        unset($row);

        echo json_encode([
            'draw'            => $draw,
            'recordsTotal'    => $recordsTotal,
            'recordsFiltered' => $recordsFiltered,
            'data'            => $rows,
        ]);

    } catch (PDOException $e) {
        echo json_encode([
            'draw'            => $draw,
            'recordsTotal'    => 0,
            'recordsFiltered' => 0,
            'data'            => [],
            'error'           => 'Database error: ' . $e->getMessage(),
        ]);
    }
    exit();
}

// ─── ADD ───────────────────────────────────────────────────────────────────────
if ($action === 'add') {
    $f = collectFields($_POST);
    if (!$f) {
        echo json_encode(['status' => '0', 'msg' => 'JAP Service ID, Name, Category and Our Rate are required.']);
        exit();
    }

    try {
        $dup = $pdo->prepare("SELECT id FROM smm_services WHERE jap_service_id = :jap_id");
        $dup->bindParam(':jap_id', $f['jap_service_id'], PDO::PARAM_INT);
        $dup->execute();
        if ($dup->fetch()) {
            echo json_encode(['status' => '0', 'msg' => 'A service with this JAP Service ID already exists.']);
            exit();
        }

        $stmt = $pdo->prepare("
            INSERT INTO smm_services
                (jap_service_id, category, name, type, jap_rate, our_rate,
                 min_quantity, max_quantity, refill, cancel, status)
            VALUES
                (:jap_service_id, :category, :name, :type, :jap_rate, :our_rate,
                 :min_quantity, :max_quantity, :refill, :cancel, :status)
        ");
        $stmt->bindValue(':jap_service_id', $f['jap_service_id'], PDO::PARAM_INT);
        $stmt->bindValue(':category',       $f['category'],       PDO::PARAM_STR);
        $stmt->bindValue(':name',           $f['name'],           PDO::PARAM_STR);
        $stmt->bindValue(':type',           $f['type'],           PDO::PARAM_STR);
        $stmt->bindValue(':jap_rate',       $f['jap_rate'],       PDO::PARAM_STR);
        $stmt->bindValue(':our_rate',       $f['our_rate'],       PDO::PARAM_STR);
        $stmt->bindValue(':min_quantity',   $f['min_quantity'],   PDO::PARAM_INT);
        $stmt->bindValue(':max_quantity',   $f['max_quantity'],   PDO::PARAM_INT);
        $stmt->bindValue(':refill',         $f['refill'],         PDO::PARAM_INT);
        $stmt->bindValue(':cancel',         $f['cancel'],         PDO::PARAM_INT);
        $stmt->bindValue(':status',         $f['status'],         PDO::PARAM_INT);

        if ($stmt->execute()) {
            echo json_encode(['status' => '1', 'msg' => '"' . $f['name'] . '" added successfully.']);
        } else {
            echo json_encode(['status' => '0', 'msg' => 'Failed to add service.']);
        }
    } catch (PDOException $e) {
        echo json_encode(['status' => '0', 'msg' => 'Database error: ' . $e->getMessage()]);
    }
    exit();
}

// ─── EDIT ──────────────────────────────────────────────────────────────────────
if ($action === 'edit') {
    $id = filter_var($_POST['id'] ?? '', FILTER_VALIDATE_INT);
    if (!$id) {
        echo json_encode(['status' => '0', 'msg' => 'Invalid service ID.']);
        exit();
    }

    $f = collectFields($_POST);
    if (!$f) {
        echo json_encode(['status' => '0', 'msg' => 'JAP Service ID, Name, Category and Our Rate are required.']);
        exit();
    }

    try {
        $chk = $pdo->prepare("SELECT id FROM smm_services WHERE id = :id");
        $chk->bindParam(':id', $id, PDO::PARAM_INT);
        $chk->execute();
        if (!$chk->fetch()) {
            echo json_encode(['status' => '0', 'msg' => 'Service not found.']);
            exit();
        }

        $dup = $pdo->prepare("SELECT id FROM smm_services WHERE jap_service_id = :jap_id AND id != :id");
        $dup->bindParam(':jap_id', $f['jap_service_id'], PDO::PARAM_INT);
        $dup->bindParam(':id',     $id,                  PDO::PARAM_INT);
        $dup->execute();
        if ($dup->fetch()) {
            echo json_encode(['status' => '0', 'msg' => 'Another service with this JAP Service ID already exists.']);
            exit();
        }

        $stmt = $pdo->prepare("
            UPDATE smm_services SET
                jap_service_id = :jap_service_id,
                category       = :category,
                name           = :name,
                type           = :type,
                jap_rate       = :jap_rate,
                our_rate       = :our_rate,
                min_quantity   = :min_quantity,
                max_quantity   = :max_quantity,
                refill         = :refill,
                cancel         = :cancel,
                status         = :status
            WHERE id = :id
        ");
        $stmt->bindValue(':jap_service_id', $f['jap_service_id'], PDO::PARAM_INT);
        $stmt->bindValue(':category',       $f['category'],       PDO::PARAM_STR);
        $stmt->bindValue(':name',           $f['name'],           PDO::PARAM_STR);
        $stmt->bindValue(':type',           $f['type'],           PDO::PARAM_STR);
        $stmt->bindValue(':jap_rate',       $f['jap_rate'],       PDO::PARAM_STR);
        $stmt->bindValue(':our_rate',       $f['our_rate'],       PDO::PARAM_STR);
        $stmt->bindValue(':min_quantity',   $f['min_quantity'],   PDO::PARAM_INT);
        $stmt->bindValue(':max_quantity',   $f['max_quantity'],   PDO::PARAM_INT);
        $stmt->bindValue(':refill',         $f['refill'],         PDO::PARAM_INT);
        $stmt->bindValue(':cancel',         $f['cancel'],         PDO::PARAM_INT);
        $stmt->bindValue(':status',         $f['status'],         PDO::PARAM_INT);
        $stmt->bindValue(':id',             $id,                  PDO::PARAM_INT);

        if ($stmt->execute()) {
            echo json_encode(['status' => '1', 'msg' => '"' . $f['name'] . '" updated successfully.']);
        } else {
            echo json_encode(['status' => '0', 'msg' => 'Failed to update service.']);
        }
    } catch (PDOException $e) {
        echo json_encode(['status' => '0', 'msg' => 'Database error: ' . $e->getMessage()]);
    }
    exit();
}

// ─── DELETE ────────────────────────────────────────────────────────────────────
if ($action === 'delete') {
    $id = filter_var($_POST['id'] ?? '', FILTER_VALIDATE_INT);
    if (!$id) {
        echo json_encode(['status' => '0', 'msg' => 'Invalid service ID.']);
        exit();
    }

    try {
        $chk = $pdo->prepare("SELECT name FROM smm_services WHERE id = :id");
        $chk->bindParam(':id', $id, PDO::PARAM_INT);
        $chk->execute();
        $svc = $chk->fetch(PDO::FETCH_ASSOC);
        if (!$svc) {
            echo json_encode(['status' => '0', 'msg' => 'Service not found.']);
            exit();
        }

        $stmt = $pdo->prepare("DELETE FROM smm_services WHERE id = :id");
        $stmt->bindParam(':id', $id, PDO::PARAM_INT);
        if ($stmt->execute()) {
            echo json_encode(['status' => '1', 'msg' => '"' . $svc['name'] . '" deleted successfully.']);
        } else {
            echo json_encode(['status' => '0', 'msg' => 'Failed to delete service.']);
        }
    } catch (PDOException $e) {
        echo json_encode(['status' => '0', 'msg' => 'Database error: ' . $e->getMessage()]);
    }
    exit();
}

// ─── UNKNOWN ───────────────────────────────────────────────────────────────────
echo json_encode(['status' => '0', 'msg' => 'Unknown action.']);
?>