<?php
// File ini hanya untuk AJAX, tidak perlu header/footer HTML
require_once '../includes/db.php';

// Hanya izinkan admin yang login
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    http_response_code(403); // Forbidden
    echo json_encode(['status' => 'error', 'message' => 'Akses ditolak.']);
    exit;
}

// Hanya terima metode POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405); // Method Not Allowed
    exit;
}

// Ambil data JSON yang dikirim oleh JavaScript
$data = json_decode(file_get_contents('php://input'), true);

if (!isset($data['type']) || !isset($data['order']) || !is_array($data['order'])) {
    http_response_code(400); // Bad Request
    echo json_encode(['status' => 'error', 'message' => 'Data tidak valid.']);
    exit;
}

$type = $data['type'];
$order_ids = $data['order'];
$table_name = '';

// Tentukan tabel mana yang akan di-update
switch ($type) {
    case 'courses':
        $table_name = 'courses';
        break;
    case 'lessons':
        $table_name = 'lessons';
        break;
    default:
        http_response_code(400);
        echo json_encode(['status' => 'error', 'message' => 'Tipe tidak valid.']);
        exit;
}

try {
    $pdo->beginTransaction();

    $sql = "UPDATE {$table_name} SET sort_order = ? WHERE id = ?";
    $stmt = $pdo->prepare($sql);

    // Loop melalui array urutan dan update setiap baris
    foreach ($order_ids as $index => $id) {
        $sort_order = $index + 1; // Urutan dimulai dari 1
        $stmt->execute([$sort_order, $id]);
    }

    $pdo->commit();
    
    header('Content-Type: application/json');
    echo json_encode(['status' => 'success', 'message' => 'Urutan berhasil disimpan.']);

} catch (PDOException $e) {
    $pdo->rollBack();
    http_response_code(500); // Internal Server Error
    echo json_encode(['status' => 'error', 'message' => 'Database error: ' . $e->getMessage()]);
}