<?php
declare(strict_types=1);
ob_start();

header('Content-Type: application/json');
header('Cache-Control: no-store');

require_once __DIR__ . '/includes/config.php';

// PHP version check — PhpSpreadsheet 3.x needs PHP 8.1+
if (version_compare(PHP_VERSION, '8.1.0', '<')) {
    ob_clean();
    http_response_code(500);
    echo json_encode([
        'error' => 'Votre serveur utilise PHP ' . PHP_VERSION . '. Le traitement Excel nécessite PHP 8.1 minimum. Veuillez changer la version PHP dans votre panneau de contrôle (cPanel → PHP Version → 8.1 ou 8.2).'
    ]);
    exit;
}

require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/excel_reader.php';

try {
    // Validate upload
    if (!isset($_FILES['excel_file']) || $_FILES['excel_file']['error'] !== UPLOAD_ERR_OK) {
        $code = $_FILES['excel_file']['error'] ?? -1;
        throw new RuntimeException("Upload error code: $code");
    }

    $file    = $_FILES['excel_file'];
    $origName = basename($file['name']);
    $ext     = strtolower(pathinfo($origName, PATHINFO_EXTENSION));

    if (!in_array($ext, ALLOWED_EXTENSIONS, true)) {
        throw new RuntimeException("Unsupported file type: .$ext");
    }
    if ($file['size'] > MAX_UPLOAD_BYTES) {
        throw new RuntimeException("File too large (max " . MAX_UPLOAD_SIZE_MB . "MB)");
    }

    // Save file
    $token    = bin2hex(random_bytes(16));
    $safeName = $token . '.' . $ext;
    $destPath = UPLOADS_DIR . '/' . $safeName;

    if (!move_uploaded_file($file['tmp_name'], $destPath)) {
        throw new RuntimeException('Failed to save uploaded file');
    }

    // Settings from form
    $urlColumn  = preg_replace('/[^A-Za-z]/', '', $_POST['url_column'] ?? '') ?: '';
    $maxRows    = max(0, (int)($_POST['max_rows']    ?? 0));
    $timeoutS   = min(120, max(5,  (int)($_POST['timeout_s']   ?? DEFAULT_TIMEOUT)));
    $delayMs    = min(10000, max(0, (int)($_POST['delay_ms']   ?? DEFAULT_DELAY_MS)));
    $maxRetries = min(10, max(1,   (int)($_POST['max_retries'] ?? DEFAULT_MAX_RETRIES)));
    $userAgent  = strip_tags(trim($_POST['user_agent'] ?? ''));

    // Read URLs
    $reader    = new ExcelReader($destPath);
    $detectedCol = $reader->detectUrlColumn($urlColumn);
    $urls      = $reader->readUrls($detectedCol, $maxRows);

    if (empty($urls)) {
        unlink($destPath);
        throw new RuntimeException("No valid URLs found in column '$detectedCol'. Check your file and column setting.");
    }

    // Create job
    $jobId = Db::createJob([
        'token'         => $token,
        'filename'      => $safeName,
        'original_name' => $origName,
        'url_column'    => $detectedCol,
        'timeout_s'     => $timeoutS,
        'delay_ms'      => $delayMs,
        'max_retries'   => $maxRetries,
        'user_agent'    => $userAgent,
    ]);

    Db::setJobTotalRows($jobId, count($urls));
    Db::insertResultBatch($jobId, $urls);

    // Processing is done by the frontend via api.php?action=process
    // No exec() needed — works on all shared hosting configurations
    ob_clean();
    echo json_encode([
        'success'  => true,
        'job_id'   => $jobId,
        'token'    => $token,
        'total'    => count($urls),
        'column'   => $detectedCol,
    ]);

} catch (Throwable $e) {
    ob_clean();
    http_response_code(400);
    echo json_encode(['error' => $e->getMessage()]);
}
