<?php
error_reporting(0);
header('Content-Type: application/json');
include 'config.php';
session_start();

try {
    $type = $_POST['type'] ?? '';
    
    $admin_username = $_SESSION['admin_user'] ?? '';
    $admin_password = $_SESSION['admin_pass'] ?? '';

    function validateModerator($conn, $username, $password) {
        if(empty($username) || empty($password)) return null;
        $stmt = $conn->prepare("SELECT extra_json FROM modarator_permissions WHERE username=? AND password=? LIMIT 1");
        $stmt->bind_param("ss", $username, $password);
        $stmt->execute();
        $result = $stmt->get_result();
        if ($row = $result->fetch_assoc()) {
            $extra = json_decode($row['extra_json'], true);
            $fulfillment = $extra['order_fulfillment'] ?? 'No';
            return $fulfillment;
        }
        return null;
    }

    if ($type === 'check_permission') {
        if (empty($admin_username) || empty($admin_password)) {
            echo json_encode(["status" => "error", "message" => "Missing credentials in session", "force_logout" => true]);
            exit;
        }
        $fulfillment = validateModerator($conn, $admin_username, $admin_password);
        if ($fulfillment === 'Yes') {
            echo json_encode(["status" => "success", "fulfillment" => "Yes"]);
        } else {
            echo json_encode(["status" => "error", "message" => "Permission denied", "force_logout" => true]);
        }
        exit;
    }

    if ($type === 'get_all' || $type === 'complete' || $type === 'fail') {
        if (empty($admin_username) || empty($admin_password)) {
            http_response_code(403);
            echo json_encode(["status" => "error", "message" => "Session Expired. Please Login Again.", "force_logout" => true]);
            exit;
        }
        $fulfillment = validateModerator($conn, $admin_username, $admin_password);
        if ($fulfillment !== 'Yes') {
            http_response_code(403);
            echo json_encode(["status" => "error", "message" => "Access denied: Order Fulfillment permission required", "force_logout" => true]);
            exit;
        }
    }

    if ($type === 'get_all') {
        $status = $conn->real_escape_string($_POST['status'] ?? '');
        $page = max(1, (int)($_POST['page'] ?? 1));
        $per_page = max(1, (int)($_POST['per_page'] ?? 20));
        $offset = ($page - 1) * $per_page;

        $where = "";
        if ($status && in_array($status, ['Pending', 'Success', 'Failed'])) {
            $where = " WHERE LOWER(o.status) = LOWER('$status')";
        }

        $countQuery = "SELECT COUNT(*) as total FROM product_orders o LEFT JOIN users u ON o.user_id = u.id" . $where;
        $countResult = $conn->query($countQuery);
        $total = $countResult->fetch_assoc()['total'] ?? 0;
        $last_page = ceil($total / $per_page);

        $sql = "SELECT o.*, u.username as user_username
                FROM product_orders o
                LEFT JOIN users u ON o.user_id = u.id
                " . $where . " 
                ORDER BY o.order_id DESC 
                LIMIT $offset, $per_page";
        $result = $conn->query($sql);
        $data = [];
        if ($result) {
            while ($row = $result->fetch_assoc()) {
                $row['extra_data'] = json_decode($row['extra_json'], true);
                $data[] = $row;
            }
        }

        echo json_encode([
            "status" => "success",
            "data" => $data,
            "total" => (int)$total,
            "current_page" => $page,
            "per_page" => $per_page,
            "last_page" => $last_page
        ]);
        exit;
    }

    if ($type === 'complete') {
        $order_id = $conn->real_escape_string($_POST['order_id'] ?? '');
        if (!$order_id) {
            echo json_encode(["status" => "error", "message" => "Missing order ID"]);
            exit;
        }
        
        $check = $conn->query("SELECT LOWER(status) as status_lower FROM product_orders WHERE order_id = '$order_id'");
        if (!$check || $check->num_rows === 0) {
            echo json_encode(["status" => "error", "message" => "Order not found"]);
            exit;
        }
        
        $row = $check->fetch_assoc();
        if ($row['status_lower'] !== 'pending') {
            echo json_encode(["status" => "error", "message" => "Order already processed"]);
            exit;
        }
        
        $update = $conn->query("UPDATE product_orders SET status = 'Success' WHERE order_id = '$order_id'");
        if ($update) {
            echo json_encode(["status" => "success", "message" => "Order marked as Success"]);
        } else {
            echo json_encode(["status" => "error", "message" => "Failed to update status"]);
        }
        exit;
    }

    if ($type === 'fail') {
        $order_id = $conn->real_escape_string($_POST['order_id'] ?? '');
        if (!$order_id) {
            echo json_encode(["status" => "error", "message" => "Missing order ID"]);
            exit;
        }
        
        $get = $conn->query("SELECT user_id, extra_json FROM product_orders WHERE order_id = '$order_id' AND LOWER(status) = 'pending'");
        if (!$get || $get->num_rows === 0) {
            echo json_encode(["status" => "error", "message" => "Order not found or already processed"]);
            exit;
        }
        
        $order = $get->fetch_assoc();
        $user_id = $conn->real_escape_string($order['user_id']);
        $extra = json_decode($order['extra_json'], true);
        
        $refund_amount = (float)($extra['total_amount'] ?? 0);

        if ($refund_amount <= 0) {
            echo json_encode(["status" => "error", "message" => "Invalid refund amount"]);
            exit;
        }

        $refund = $conn->query("UPDATE users SET balance = balance + $refund_amount WHERE id = '$user_id'");
        if (!$refund) {
            echo json_encode(["status" => "error", "message" => "Failed to refund user"]);
            exit;
        }

        $update = $conn->query("UPDATE product_orders SET status = 'Failed' WHERE order_id = '$order_id'");
        if ($update) {
            echo json_encode(["status" => "success", "message" => "Order Failed & ৳$refund_amount refunded"]);
        } else {
            echo json_encode(["status" => "error", "message" => "Status update failed, but refund was done"]);
        }
        exit;
    }

    echo json_encode(["status" => "error", "message" => "Invalid request type"]);

} catch (Exception $e) {
    echo json_encode(["status" => "error", "message" => "Database Error"]);
}

if(isset($conn)) $conn->close();
?>
