<?php
// api/upload-test-full.php

require_once '../../config/cors.php';
require_once '../../config/db.php';
require_once '../../config/r2.php';
require_once '../../helpers/response.php';
require_once '../../helpers/request.php';
require_once '../../helpers/auth.php';
$method = getRequestMethod();

if ($method === 'OPTIONS') {
    http_response_code(200);
    exit;
}
$user = requireAdmin(); 
if ($method !== 'POST') {
    sendError('Method not allowed', 405);
}

if (!isset($_FILES['file'])) {
    sendError('No file uploaded', 400);
}

$file = $_FILES['file'];
$title = isset($_POST['title']) ? $_POST['title'] : '';
$type = isset($_POST['type']) ? $_POST['type'] : 'audio';
$description = isset($_POST['description']) ? $_POST['description'] : '';
$podcast_id = isset($_POST['podcast_id']) && $_POST['podcast_id'] !== '' ? intval($_POST['podcast_id']) : null;
$is_premium = isset($_POST['is_premium']) && $_POST['is_premium'] === 'true' ? 1 : 0;

// Validate file type
$allowedAudio = ['audio/mpeg', 'audio/mp3', 'audio/wav', 'audio/mp4', 'audio/m4a', 'audio/x-m4a'];
$allowedVideo = ['video/mp4', 'video/mpeg', 'video/quicktime', 'video/x-msvideo'];

if ($type === 'audio' && !in_array($file['type'], $allowedAudio)) {
    sendError('Invalid audio format. Allowed: MP3, WAV, M4A', 400);
}

if ($type === 'video' && !in_array($file['type'], $allowedVideo)) {
    sendError('Invalid video format. Allowed: MP4, MPEG', 400);
}

// Generate unique filename for R2 - organized by media type
$extension = pathinfo($file['name'], PATHINFO_EXTENSION);
$safeTitle = preg_replace('/[^a-zA-Z0-9_-]/', '_', pathinfo($file['name'], PATHINFO_FILENAME));
$folder = ($type === 'audio') ? 'audio' : 'video';
$media_id = $folder . '/' . $safeTitle . '_' . uniqid() . '.' . $extension;

// Upload to R2
$uploadResult = uploadToR2($file['tmp_name'], $media_id, $file['type']);

if (!$uploadResult['success']) {
    sendError('R2 upload failed: ' . $uploadResult['error'], 500);
}

// Save to database - using media_id column
try {
    $stmt = $pdo->prepare("
        INSERT INTO media (title, description, type, media_id, podcast_id, is_premium, file_size, status) 
        VALUES (:title, :description, :type, :media_id, :podcast_id, :is_premium, :file_size, 'ready')
    ");
    
    $stmt->execute([
        ':title' => $title ?: pathinfo($file['name'], PATHINFO_FILENAME),
        ':description' => $description,
        ':type' => $type,
        ':media_id' => $media_id,
        ':podcast_id' => $podcast_id,
        ':is_premium' => $is_premium,
        ':file_size' => $file['size']
    ]);
    
    $db_id = $pdo->lastInsertId();
    
    sendSuccess([
        'id' => $db_id,
        'title' => $title,
        'description' => $description,
        'type' => $type,
        'media_id' => $media_id,
        'url' => $uploadResult['url'],
        'file_size' => $file['size'],
        'podcast_id' => $podcast_id,
        'is_premium' => $is_premium,
        'status' => 'ready'
    ], 'File uploaded to R2 successfully');
    
} catch (PDOException $e) {
    // Delete from R2 if database insert fails
    deleteFromR2($media_id);
    sendError('Database error: ' . $e->getMessage(), 500);
}
?>