<?php
declare(strict_types=1);

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'error' => 'Invalid request method.']);
    exit;
}

if (!isset($_FILES['sahur_file'])) {
    echo json_encode(['success' => false, 'error' => 'No file uploaded.']);
    exit;
}

$file = $_FILES['sahur_file'];

// Basic validation
if ($file['error'] !== UPLOAD_ERR_OK) {
    echo json_encode(['success' => false, 'error' => 'Upload error: ' . $file['error']]);
    exit;
}

$ext = pathinfo($file['name'], PATHINFO_EXTENSION);
if (strtolower($ext) !== 'mp3') {
    echo json_encode(['success' => false, 'error' => 'Only MP3 files are allowed.']);
    exit;
}

$targetDir = __DIR__ . '/../assets/audio/';
if (!is_dir($targetDir)) {
    mkdir($targetDir, 0775, true);
}

$targetPath = $targetDir . 'sahur.mp3';

if (move_uploaded_file($file['tmp_name'], $targetPath)) {
    echo json_encode(['success' => true]);
} else {
    echo json_encode(['success' => false, 'error' => 'Failed to save file.']);
}
