<?php
session_start();
// Image upload handler
$pdo = require __DIR__ . '/../config/db.php';


if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['image'])) {
    $format_id = $_POST['format_id'] ?? null;
    $image_type = $_POST['image_type'] ?? 'image_base'; // default to image_base if not specified
    $mediaDir = dirname(__DIR__) . '/media/';
    $tmpDir = $mediaDir . 'tmp/';
    if (!is_dir($mediaDir)) {
        echo 'error: media directory does not exist: ' . $mediaDir;
        exit;
    }
    // If no format_id, treat as Add New Format: upload to tmp folder
    if (!$format_id) {
        if (!is_dir($tmpDir)) {
            if (!mkdir($tmpDir, 0777, true)) {
                echo 'error: failed to create tmp directory: ' . $tmpDir;
                exit;
            }
        }
        $fileName = session_id() . '_' . time() . '_' . basename($_FILES['image']['name']);
        $targetFile = $tmpDir . $fileName;
        $moveResult = move_uploaded_file($_FILES['image']['tmp_name'], $targetFile);
        if ($moveResult) {
            echo 'success:tmp/' . $fileName;
            exit;
        } else {
            echo 'error: move_uploaded_file failed (add new). Path: ' . $targetFile . ' | _FILES: ' . print_r($_FILES, true);
            exit;
        }
    } else {
        // Edit mode: support both image_base and image_comp
        $allowedFields = ['image_base', 'image_comp'];
        if (!in_array($image_type, $allowedFields)) {
            echo 'error: invalid image_type';
            exit;
        }
        $fileName = time() . '_' . basename($_FILES['image']['name']);
        $targetFile = $mediaDir . $fileName;
        $moveResult = move_uploaded_file($_FILES['image']['tmp_name'], $targetFile);
        if ($moveResult && $format_id) {
            try {
                $sql = "UPDATE sites SET $image_type = :fileName WHERE id = :format_id";
                $stmt = $pdo->prepare($sql);
                $stmt->execute([':fileName' => $fileName, ':format_id' => $format_id]);
                echo 'success:' . $fileName;
                exit;
            } catch (PDOException $e) {
                error_log('PDOException: ' . $e->getMessage());
                echo 'error: PDOException: ' . $e->getMessage();
                exit;
            }
        } else {
            echo 'error: move_uploaded_file failed. Path: ' . $targetFile . ' | format_id: ' . $format_id . ' | _FILES: ' . print_r($_FILES, true);
            exit;
        }
    }
}
?>
