<?php
include 'layouts/session.php';
include 'layouts/dbconn.php';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    try {
        $conn->begin_transaction();

        // Handle file upload
        if (isset($_FILES['logo']) && $_FILES['logo']['error'] == 0) {
            $allowed = ['jpg', 'jpeg', 'png'];
            $filename = $_FILES['logo']['name'];
            $filetype = pathinfo($filename, PATHINFO_EXTENSION);

            if (in_array(strtolower($filetype), $allowed)) {
                // Create uploads directory if it doesn't exist
                $upload_dir = 'uploads/';
                if (!file_exists($upload_dir)) {
                    mkdir($upload_dir, 0777, true);
                }

                // Generate unique filename
                $new_filename = 'logo_' . time() . '.' . $filetype;
                $upload_path = $upload_dir . $new_filename;

                if (move_uploaded_file($_FILES['logo']['tmp_name'], $upload_path)) {
                    // Update logo path in settings
                    $stmt = $conn->prepare("INSERT INTO settings (setting_key, setting_value) 
                                          VALUES ('logo_path', ?) 
                                          ON DUPLICATE KEY UPDATE setting_value = ?");
                    $stmt->bind_param("ss", $upload_path, $upload_path);
                    $stmt->execute();
                }
            }
        }

        // Update other settings
        if (isset($_POST['settings'])) {
            $stmt = $conn->prepare("UPDATE settings SET setting_value = ? WHERE setting_key = ?");

            foreach ($_POST['settings'] as $key => $value) {
                $stmt->bind_param("ss", $value, $key);
                $stmt->execute();
            }
        }

        $conn->commit();
        $_SESSION['success_msg'] = "Settings updated successfully";
        
    } catch (Exception $e) {
        $conn->rollback();
        $_SESSION['error_msg'] = "Error updating settings: " . $e->getMessage();
    }
}

header("Location: settings.php");
exit();
?>