<?php
require_once 'config.php';
require_once 'includes/db.php';
require_once 'includes/functions.php';
require_login();

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['order'])) {
    $order = $_POST['order'];
    $user_id = $_SESSION['user_id'];
    
    try {
        $pdo->beginTransaction();
        $stmt = $pdo->prepare("UPDATE videos SET position = ? WHERE id = ? AND user_id = ?");
        
        foreach ($order as $item) {
            if(isset($item['position']) && isset($item['id'])) {
                $stmt->execute([
                    $item['position'],
                    $item['id'],
                    $user_id
                ]);
            }
        }
        
        $pdo->commit();
        echo json_encode(["status" => "success"]);
    } catch(Exception $e) {
        $pdo->rollBack();
        http_response_code(500);
        echo json_encode(["status" => "error", "message" => $e->getMessage()]);
    }
}

