<?php
session_start();
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

include '../includes/db.php'; // Your database connection

// Define upload folder
$uploadDir = '../uploads/about/';
if (!is_dir($uploadDir)) mkdir($uploadDir, 0777, true);

// Helper function to handle uploads
function uploadImage($fileInput, $existingPath) {
    global $uploadDir;
    $imagePath = $existingPath;

    if (isset($_FILES[$fileInput]) && $_FILES[$fileInput]['error'] === UPLOAD_ERR_OK) {
        $fileName = time() . "_" . basename($_FILES[$fileInput]['name']);
        $targetFile = $uploadDir . $fileName;

        $allowed = ['jpg','jpeg','png','gif','webp'];
        $ext = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
        if (!in_array($ext, $allowed)) return ['error' => "Only JPG, PNG, GIF, WEBP allowed"];

        if (move_uploaded_file($_FILES[$fileInput]['tmp_name'], $targetFile)) {
            $imagePath = './uploads/about/' . $fileName;
        } else {
            return ['error' => "Failed to upload $fileInput"];
        }
    }

    return ['path' => $imagePath];
}

// Sections array for easier loop
$sections = [
    'who_we_are' => ['label' => 'Who We Are'],
    'mission_vision' => ['label' => 'Mission & Vision'],
    'ceo_message' => ['label' => 'CEO Message'],
    'quality_accreditation' => ['label' => 'Quality & Accreditation'],
];

// Handle POST
$success = '';
$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    foreach ($sections as $table => $info) {
        $text = $_POST[$table . '_text'] ?? '';
        $existingImage = $_POST[$table . '_existing_image'] ?? '';

        $upload = uploadImage($table . '_image', $existingImage);
        if (isset($upload['error'])) {
            $errors[] = $upload['error'];
            continue;
        }
        $imagePath = $upload['path'];

        // Check if row exists
        $check = $conn->query("SELECT id FROM $table LIMIT 1")->fetch_assoc();
        if ($check) {
            $stmt = $conn->prepare("UPDATE $table SET body_text=?, image=? WHERE id=?");
            $stmt->bind_param("ssi", $text, $imagePath, $check['id']);
        } else {
            $stmt = $conn->prepare("INSERT INTO $table (body_text, image) VALUES (?, ?)");
            $stmt->bind_param("ss", $text, $imagePath);
        }
        if (!$stmt->execute()) $errors[] = "Failed to save $info[label]: " . $stmt->error;
    }

    if (empty($errors)) $success = "All sections saved successfully!";
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<?php include 'header.php'; ?>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Edit About Page</title>

<!-- TinyMCE -->
<script src="https://cdn.jsdelivr.net/npm/tinymce@6/tinymce.min.js"></script>
<script>
tinymce.init({
    selector: '.tinymce',
    height: 300,
    menubar: true,
    plugins: 'advlist autolink lists link image charmap preview anchor searchreplace visualblocks code fullscreen insertdatetime media table paste help wordcount',
    toolbar: 'undo redo | formatselect | fontsizeselect | bold italic underline strikethrough | forecolor backcolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | blockquote removeformat | table | link image media | code preview fullscreen | help',
    toolbar_mode: 'wrap',
    branding: false,
    image_title: true,
    automatic_uploads: true,
    file_picker_types: 'image',
    file_picker_callback: function(cb, value, meta){
        let input = document.createElement('input');
        input.setAttribute('type','file');
        input.setAttribute('accept','image/*');
        input.onchange = function(){
            let file = this.files[0];
            let reader = new FileReader();
            reader.onload = function(){
                let id = 'blobid'+(new Date()).getTime();
                let blobCache = tinymce.activeEditor.editorUpload.blobCache;
                let base64 = reader.result.split(',')[1];
                let blobInfo = blobCache.create(id, file, base64);
                blobCache.add(blobInfo);
                cb(blobInfo.blobUri(), {title:file.name});
            };
            reader.readAsDataURL(file);
        };
        input.click();
    }
    
     
});
</script>

<style>
body { font-family: Poppins; background: #f4f4f4; margin:0; padding:0; }
.container { max-width: 900px; margin: 30px auto; background: #fff; padding: 30px; border-radius: 12px; box-shadow:0 8px 20px rgba(0,0,0,0.1); }
h2 { text-align:center; margin-bottom: 25px; }
form label { font-weight:bold; margin-top:15px; display:block; }
input[type="file"], textarea { width:100%; margin-bottom:15px; padding:10px; border-radius:6px; border:1px solid #ccc; }
button { background:#004aad; color:#fff; border:none; padding:12px 25px; border-radius:6px; cursor:pointer; }
button:hover { background:#003a8c; }
img { margin-top:10px; border:1px solid #ccc; border-radius:6px; max-width:200px; }
.success { color:green; font-weight:bold; margin-top:10px; }
.error { color:red; font-weight:bold; margin-top:10px; }
</style>
</head>
<body>

<div class="container">
<h2>Edit About Page</h2>

<?php
if(!empty($errors)) foreach($errors as $e) echo "<p class='error'>$e</p>";
if(!empty($success)) echo "<p class='success'>$success</p>";
?>

<form method="POST" enctype="multipart/form-data">

<?php foreach($sections as $table => $info):
    $row = $conn->query("SELECT * FROM $table LIMIT 1")->fetch_assoc();
?>
<label><?= $info['label'] ?> Text:</label>
<textarea name="<?= $table ?>_text" class="tinymce"><?= htmlspecialchars($row['body_text'] ?? '') ?></textarea>

<label><?= $info['label'] ?> Image:</label>
<input type="file" name="<?= $table ?>_image">
<input type="hidden" name="<?= $table ?>_existing_image" value="<?= htmlspecialchars($row['image'] ?? '') ?>">
<?php if(!empty($row['image'])): ?>
<p>Current Image:</p>
<img src="<?= $row['image'] ?>" alt="<?= $info['label'] ?>">
<?php endif; ?>

<hr>
<?php endforeach; ?>

<button type="submit">Save All Changes</button>
</form>
</div>

</body>
</html>
