<?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']) : '';

$valid_statuses = ['Pending','In progress','Processing','Completed','Partial','Cancelled','Refunded'];

// ─── GET ORDER DETAIL ──────────────────────────────────────────────────────────
if ($action === 'get_detail') {
    $id = filter_var($_POST['id'] ?? '', FILTER_VALIDATE_INT);
    if (!$id) {
        echo json_encode(['status' => '0', 'msg' => 'Invalid order ID.']);
        exit();
    }

    try {
        $stmt = $pdo->prepare("
            SELECT o.*,
                   u.username, u.full_name, u.email,
                   ss.name AS service_name
            FROM smm_orders o
            LEFT JOIN users u         ON o.user_id = u.id
            LEFT JOIN smm_services ss ON o.smm_service_id = ss.id
            WHERE o.id = :id
        ");
        $stmt->bindParam(':id', $id, PDO::PARAM_INT);
        $stmt->execute();
        $order = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$order) {
            echo json_encode(['status' => '0', 'msg' => 'Order not found.']);
        } else {
            echo json_encode(['status' => '1', 'order' => $order]);
        }
    } catch (PDOException $e) {
        echo json_encode(['status' => '0', 'msg' => 'Database error: ' . $e->getMessage()]);
    }

// ─── UPDATE STATUS ─────────────────────────────────────────────────────────────
} elseif ($action === 'update_status') {
    $id     = filter_var($_POST['id'] ?? '', FILTER_VALIDATE_INT);
    $status = isset($_POST['status']) && in_array($_POST['status'], $valid_statuses) ? $_POST['status'] : '';
    $notes  = isset($_POST['notes']) ? trim($_POST['notes']) : null;

    if (!$id) {
        echo json_encode(['status' => '0', 'msg' => 'Invalid order ID.']);
        exit();
    }
    if (empty($status)) {
        echo json_encode(['status' => '0', 'msg' => 'Invalid status value.']);
        exit();
    }

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

        $stmt = $pdo->prepare("UPDATE smm_orders SET status = :status, notes = :notes WHERE id = :id");
        $stmt->bindParam(':status', $status, PDO::PARAM_STR);
        $stmt->bindParam(':notes',  $notes,  PDO::PARAM_STR);
        $stmt->bindParam(':id',     $id,     PDO::PARAM_INT);

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

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

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

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

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