<?php
include '../db.php';

$uploadDir = __DIR__ . "/uploads/";

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(204);
    exit();
}

function ensureUploadDir($uploadDir) {
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0777, true);
    }
}

function saveUploadedFile($originalName, $tmpName, $uploadDir) {
    ensureUploadDir($uploadDir);

    $safeName = preg_replace("/[^A-Za-z0-9_.-]/", "_", basename($originalName));
    $filename = time() . "_" . uniqid() . "_" . $safeName;
    $targetFile = $uploadDir . $filename;

    if (move_uploaded_file($tmpName, $targetFile)) {
        return "/uploads/" . $filename;
    }

    return null;
}

function uploadFlatImage($fieldName, $uploadDir) {
    if (!isset($_FILES[$fieldName]) || $_FILES[$fieldName]['error'] !== UPLOAD_ERR_OK) {
        return null;
    }

    return saveUploadedFile($_FILES[$fieldName]["name"], $_FILES[$fieldName]["tmp_name"], $uploadDir);
}

function uploadNestedImage($section, $fieldName, $uploadDir) {
    if (
        !isset($_FILES[$section]["error"][$fieldName]) ||
        $_FILES[$section]["error"][$fieldName] !== UPLOAD_ERR_OK
    ) {
        return null;
    }

    return saveUploadedFile(
        $_FILES[$section]["name"][$fieldName],
        $_FILES[$section]["tmp_name"][$fieldName],
        $uploadDir
    );
}

function toBool($value) {
    return filter_var($value, FILTER_VALIDATE_BOOLEAN);
}

function upsertSection($conn, $sectionData) {
    $section = $sectionData['section'];
    $paragraph1 = $sectionData['paragraph1'];
    $paragraph2 = $sectionData['paragraph2'];
    $image1 = $sectionData['image1'];
    $image2 = $sectionData['image2'];
    $removeImage1 = $sectionData['removeImage1'] ? 1 : 0;
    $removeImage2 = $sectionData['removeImage2'] ? 1 : 0;

    $stmt = $conn->prepare("SELECT id FROM about_us WHERE section=?");
    if (!$stmt) {
        throw new Exception("Failed to prepare section lookup.");
    }

    $stmt->bind_param("s", $section);
    if (!$stmt->execute()) {
        throw new Exception("Failed to fetch existing section data.");
    }

    $result = $stmt->get_result();

    if ($result && $result->num_rows > 0) {
        $sql = "UPDATE about_us
                SET paragraph1=?, paragraph2=?,
                    image1=IF(?, NULL, IFNULL(?, image1)),
                    image2=IF(?, NULL, IFNULL(?, image2))
                WHERE section=?";
        $stmt = $conn->prepare($sql);
        if (!$stmt) {
            throw new Exception("Failed to prepare update query.");
        }

        $stmt->bind_param("ssisiss", $paragraph1, $paragraph2, $removeImage1, $image1, $removeImage2, $image2, $section);
        if (!$stmt->execute()) {
            throw new Exception("Failed to update section.");
        }
    } else {
        if ($removeImage1) {
            $image1 = null;
        }
        if ($removeImage2) {
            $image2 = null;
        }

        $sql = "INSERT INTO about_us (section, paragraph1, paragraph2, image1, image2)
                VALUES (?, ?, ?, ?, ?)";
        $stmt = $conn->prepare($sql);
        if (!$stmt) {
            throw new Exception("Failed to prepare insert query.");
        }

        $stmt->bind_param("sssss", $section, $paragraph1, $paragraph2, $image1, $image2);
        if (!$stmt->execute()) {
            throw new Exception("Failed to insert section.");
        }
    }
}

$sectionsToUpdate = [];

if (!empty($_POST['section'])) {
    $section = $_POST['section'];

    if (!in_array($section, ["top", "bottom"], true)) {
        http_response_code(400);
        echo json_encode(["error" => "Invalid section. Expected top or bottom."]);
        exit();
    }

    $sectionsToUpdate[$section] = [
        "section" => $section,
        "paragraph1" => $_POST['paragraph1'] ?? "",
        "paragraph2" => $_POST['paragraph2'] ?? "",
        "image1" => uploadFlatImage("image1", $uploadDir),
        "image2" => uploadFlatImage("image2", $uploadDir),
        "removeImage1" => toBool($_POST['removeImage1'] ?? false),
        "removeImage2" => toBool($_POST['removeImage2'] ?? false),
    ];
}

foreach (["top", "bottom"] as $section) {
    if (isset($_POST[$section]) && is_array($_POST[$section])) {
        $sectionsToUpdate[$section] = [
            "section" => $section,
            "paragraph1" => $_POST[$section]['paragraph1'] ?? "",
            "paragraph2" => $_POST[$section]['paragraph2'] ?? "",
            "image1" => uploadNestedImage($section, "image1", $uploadDir),
            "image2" => uploadNestedImage($section, "image2", $uploadDir),
            "removeImage1" => toBool($_POST[$section]['removeImage1'] ?? false),
            "removeImage2" => toBool($_POST[$section]['removeImage2'] ?? false),
        ];
    }
}

if (empty($sectionsToUpdate)) {
    http_response_code(400);
    echo json_encode(["error" => "No valid section payload found."]);
    exit();
}

try {
    foreach ($sectionsToUpdate as $sectionData) {
        upsertSection($conn, $sectionData);
    }

    echo json_encode([
        "success" => true,
        "updatedSections" => array_values(array_keys($sectionsToUpdate)),
    ]);
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode([
        "success" => false,
        "message" => $e->getMessage(),
    ]);
}

$conn->close();
