<?php
session_start();
include('includes/config.php');

$response = ['status' => 'error', 'message' => 'Something went wrong'];

try {
    $themeId   = $_POST['themeId'] ?? null;
    $themeName = $_POST['themeName'] ?? '';
    $themeColor = $_POST['themeColor'] ?? '#000000';
    $oldLogo   = $_POST['oldLogo'] ?? '';

    $uploadDir = "../assets/img/";   // Actual folder to store files
    $dbPath    = "assets/img/";      // Path to store in database

    $logoPath = $oldLogo; // default keep old one

    // ✅ Handle new file upload
    if (!empty($_FILES['logo']['name'])) {
        $fileName = time() . "_" . basename($_FILES['logo']['name']);
        $targetFile = $uploadDir . $fileName;

        // Validate image
        $check = getimagesize($_FILES['logo']['tmp_name']);
        if ($check === false) {
            throw new Exception("Uploaded file is not an image.");
        }

        if (move_uploaded_file($_FILES['logo']['tmp_name'], $targetFile)) {
            $logoPath = $dbPath . $fileName; // Save clean path in DB
        } else {
            throw new Exception("Failed to upload image.");
        }
    }

    if ($themeId) {
        // Update
        $sql = "UPDATE theme SET name = :name, color = :color, logo = :logo WHERE id = :id";
        $stmt = $dbh->prepare($sql);
        $stmt->bindParam(':id', $themeId, PDO::PARAM_INT);
    } else {
        // Insert
        $sql = "INSERT INTO theme (name, color, logo) VALUES (:name, :color, :logo)";
        $stmt = $dbh->prepare($sql);
    }

    $stmt->bindParam(':name', $themeName, PDO::PARAM_STR);
    $stmt->bindParam(':color', $themeColor, PDO::PARAM_STR);
    $stmt->bindParam(':logo', $logoPath, PDO::PARAM_STR);

    if ($stmt->execute()) {
    $_SESSION['logo'] = $logoPath;  // ✅ force update session
    $response = ['status' => 'success', 'message' => 'Theme saved successfully!'];
}


} catch (Exception $e) {
    $response = ['status' => 'error', 'message' => $e->getMessage()];
}

echo json_encode($response);
?>
