<?php

header('Content-Type: application/json');
$response = ['success' => false, 'orders' => [], 'pagination' => null, 'message' => 'Gagal memuat riwayat pesanan.'];

require_once __DIR__ . '/../../config/config.php';
require_once __DIR__ . '/../../includes/session.php';
require_once __DIR__ . '/../../lib/Auth.php';
require_once __DIR__ . '/../../includes/functions.php';

if (!Auth::isLoggedIn()) { http_response_code(401); $response['message'] = 'Sesi berakhir.'; echo json_encode($response); exit; }

if (!isset($pdo) || !$pdo instanceof PDO) { http_response_code(500); error_log("PDO object not available in get_order_history.php"); $response['message'] = 'Koneksi database gagal.'; echo json_encode($response); exit; }

try {
    $limit = filter_input(INPUT_GET, 'limit', FILTER_VALIDATE_INT, ['options' => ['default' => 10, 'min_range' => 5, 'max_range' => 100]]);
    $page = filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT, ['options' => ['default' => 1, 'min_range' => 1]]);
    $status = $_GET['status'] ?? 'all';
    $sortBy = $_GET['sort_by'] ?? 'o.created_at';
    $sortType = $_GET['sort_type'] ?? 'DESC';
    $searchColumn = $_GET['search_column'] ?? 'o.id';
    $searchKeyword = filter_input(INPUT_GET, 'search_keyword', FILTER_SANITIZE_SPECIAL_CHARS) ?? '';
    $dateStart = $_GET['date_start'] ?? '';
    $dateEnd = $_GET['date_end'] ?? '';

    $userId = $_SESSION['user_id'];
    $offset = ($page - 1) * $limit;

    $allowedSortColumns = ['o.created_at', 'o.id', 's.name', 'o.price', 'o.quantity', 'o.status'];
    $allowedSortTypes = ['ASC', 'DESC'];
    if (!in_array($sortBy, $allowedSortColumns)) { $sortBy = 'o.created_at'; }
    if (!in_array(strtoupper($sortType), $allowedSortTypes)) { $sortType = 'DESC'; }

    $allowedSearchColumns = ['o.id', 'o.target', 's.name'];
    if (!in_array($searchColumn, $allowedSearchColumns)) { $searchColumn = 'o.id'; }
    $sqlSelect = "SELECT
                    o.id, o.created_at, o.updated_at, o.target, o.quantity, o.price, o.status,
                    o.start_count, o.remains, o.order_source, o.ip_address,
                    s.name as service_name
                  ";
    // ========================================================
    $sqlFrom = "FROM orders o JOIN services s ON o.service_id = s.id ";
    $sqlWhereBase = "WHERE o.user_id = :user_id ";
    $params = [':user_id' => $userId];
    $whereClauses = [];

    if ($status !== 'all') { $validStatuses = ['pending', 'processing', 'in progress', 'success', 'error', 'partial', 'canceled']; if (in_array($status, $validStatuses)) { $whereClauses[] = "o.status = :status"; $params[':status'] = $status; } }
    if (!empty($searchKeyword)) { if ($searchColumn === 'o.id') { if (is_numeric($searchKeyword)) { $whereClauses[] = "o.id = :search_keyword_id"; $params[':search_keyword_id'] = (int)$searchKeyword; } else { $whereClauses[] = "1 = 0"; } } elseif ($searchColumn === 'o.target') { $whereClauses[] = "o.target LIKE :search_keyword"; $params[':search_keyword'] = '%' . $searchKeyword . '%'; } elseif ($searchColumn === 's.name') { $whereClauses[] = "s.name LIKE :search_keyword"; $params[':search_keyword'] = '%' . $searchKeyword . '%'; } }
    if (!empty($dateStart) && preg_match('/^\d{4}-\d{2}-\d{2}$/', $dateStart)) { $whereClauses[] = "DATE(o.created_at) >= :date_start"; $params[':date_start'] = $dateStart; }
    if (!empty($dateEnd) && preg_match('/^\d{4}-\d{2}-\d{2}$/', $dateEnd)) { $whereClauses[] = "DATE(o.created_at) <= :date_end"; $params[':date_end'] = $dateEnd; }

    $sqlWhere = $sqlWhereBase . (!empty($whereClauses) ? " AND " . implode(" AND ", $whereClauses) : "");

    $totalOrders = 0; $totalPages = 1;
    $sqlCount = "SELECT COUNT(o.id) " . $sqlFrom . $sqlWhere;
    try {
        $stmtCount = $pdo->prepare($sqlCount);
        $stmtCount->execute($params);
        $totalOrders = (int)$stmtCount->fetchColumn();
        $totalPages = $totalOrders > 0 ? ceil($totalOrders / $limit) : 1;
        if ($page > $totalPages) { $page = $totalPages; $offset = ($page - 1) * $limit; }
        elseif ($page < 1) { $page = 1; $offset = 0; }
    } catch (\PDOException $e) { error_log("Error counting order history: " . $e->getMessage()); throw $e; }

    $orders = [];
    $sqlData = $sqlSelect . $sqlFrom . $sqlWhere . " ORDER BY {$sortBy} {$sortType} LIMIT :limit OFFSET :offset";
    try {
        $stmtData = $pdo->prepare($sqlData);
        $stmtData->bindParam(':user_id', $userId, PDO::PARAM_INT);
        if (isset($params[':status'])) { $stmtData->bindParam(':status', $params[':status']); }
        if (isset($params[':search_keyword_id'])) { $stmtData->bindParam(':search_keyword_id', $params[':search_keyword_id'], PDO::PARAM_INT); }
        elseif (isset($params[':search_keyword'])) { $stmtData->bindParam(':search_keyword', $params[':search_keyword']); }
        if (isset($params[':date_start'])) { $stmtData->bindParam(':date_start', $params[':date_start']); }
        if (isset($params[':date_end'])) { $stmtData->bindParam(':date_end', $params[':date_end']); }
        $stmtData->bindParam(':limit', $limit, PDO::PARAM_INT);
        $stmtData->bindParam(':offset', $offset, PDO::PARAM_INT);
        $stmtData->execute();
        $orders = $stmtData->fetchAll(PDO::FETCH_ASSOC);

        $response['success'] = true;
        $response['orders'] = $orders; 
        $response['pagination'] = [ 'totalItems' => $totalOrders, 'totalPages' => $totalPages, 'currentPage' => $page, 'limit' => $limit, 'offset' => $offset ];
        unset($response['message']);

    } catch (\PDOException $e) { error_log("Error fetching order history data: " . $e->getMessage()); $response['message'] = "Gagal mengambil data riwayat pesanan."; http_response_code(500); }

} catch (\Throwable $e) { error_log("AJAX Get Order History General Error: " . $e->getMessage()); $response['message'] = "Terjadi kesalahan internal server."; if (defined('DEBUG_MODE') && DEBUG_MODE === true) { $response['debug_php'] = $e->getMessage(); } http_response_code(500); }

echo json_encode($response);
exit;
?>
