<?php
include('db_connection.php');

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $school_name = $_POST['school_name'];
    $school_tagline = $_POST['school_tagline'];
    $phone_no = $_POST['phone_no'];
    $email = $_POST['email'];
    $address = $_POST['address'];
    $next_term_begins = $_POST['next_term_begins'];
    $current_session = $_POST['current_session'];
    $current_term = $_POST['current_term'];

    // Fetch current settings to keep existing images if not updated
    $result = $conn->query("SELECT * FROM settings WHERE id = 1"); // Assuming there's only one settings row
    $settings = $result->fetch_assoc();

    // Handle file uploads
    $logo = $settings['logo'];
    $stamp_image = $settings['stamp_image'];

    if ($_FILES['logo']['name']) {
        $logo = basename($_FILES['logo']['name']);
        $target_path = 'uploads/' . $logo;
        move_uploaded_file($_FILES['logo']['tmp_name'], $target_path);
    }

    if ($_FILES['stamp_image']['name']) {
        $stamp_image = basename($_FILES['stamp_image']['name']);
        $target_path = 'uploads/' . $stamp_image;
        move_uploaded_file($_FILES['stamp_image']['tmp_name'], $target_path);
    }

    // Check if settings row exists
    $checkResult = $conn->query("SELECT COUNT(*) as count FROM settings WHERE id = 1");
    $row = $checkResult->fetch_assoc();

    if ($row['count'] > 0) {
        // Update settings in the database
        $stmt = $conn->prepare("UPDATE settings SET school_name = ?, school_tagline = ?, phone_no = ?, email = ?, address = ?, next_term_begins = ?, current_session = ?, current_term = ?, logo = ?, stamp_image = ? WHERE id = 1");
        $stmt->bind_param("ssssssssss", $school_name, $school_tagline, $phone_no, $email, $address, $next_term_begins, $current_session, $current_term, $logo, $stamp_image);
    } else {
        // Insert new settings row in the database
        $stmt = $conn->prepare("INSERT INTO settings (school_name, school_tagline, phone_no, email, address, next_term_begins, current_session, current_term, logo, stamp_image) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->bind_param("ssssssssss", $school_name, $school_tagline, $phone_no, $email, $address, $next_term_begins, $current_session, $current_term, $logo, $stamp_image);
    }

    if ($stmt->execute()) {
        echo "Settings updated successfully!";
    } else {
        echo "Error: " . $stmt->error;
    }

    $stmt->close();
    $conn->close();
}
?>
