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

// Fetch existing data
$about = $conn->query("SELECT * FROM about_page LIMIT 1")->fetch_assoc();

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $about_text = $_POST['about_text'];
    $ceo_name = $_POST['ceo_name'];
    $ceo_message = $_POST['ceo_message'];

    // Upload CEO photo
    $ceo_photo = $about['ceo_photo'];
    if (isset($_FILES['ceo_photo']) && $_FILES['ceo_photo']['error'] === UPLOAD_ERR_OK) {
        $targetDir = "../uploads/about/";
        if (!is_dir($targetDir)) mkdir($targetDir, 0777, true);

        $fileName = time() . "_" . basename($_FILES['ceo_photo']['name']);
        $targetFile = $targetDir . $fileName;

        // Validate image type
        $allowed = ['jpg','jpeg','png','gif','webp'];
        $fileExt = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
        if (!in_array($fileExt, $allowed)) {
            die("Only JPG, PNG, GIF, WEBP files are allowed.");
        }

        if (move_uploaded_file($_FILES['ceo_photo']['tmp_name'], $targetFile)) {
            $ceo_photo = './uploads/about/' . $fileName;
        } else {
            die("Failed to upload CEO photo. Check folder permissions.");
        }
    }

    // Update query
    $stmt = $conn->prepare("UPDATE about_page SET about_text=?, ceo_name=?, ceo_message=?, ceo_photo=? WHERE id=1");
    $stmt->bind_param("ssss", $about_text, $ceo_name, $ceo_message, $ceo_photo);
    $stmt->execute();

    $success = "About page updated successfully!";
}
?>

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

<!-- Advanced TinyMCE -->
<script src="https://cdn.jsdelivr.net/npm/tinymce@6/tinymce.min.js" referrerpolicy="origin"></script>
<script>
tinymce.init({
    selector: '.tinymce',
    height: 400,
    menubar: true,
    plugins: `
        advlist autolink lists link image charmap preview anchor
        searchreplace visualblocks code fullscreen
        insertdatetime media table paste code 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();
    },
    content_style: `
        body { font-family:Arial,sans-serif; font-size:14px }
        table { border-collapse: collapse; width:100%; }
        table, th, td { border:1px solid #ccc; padding:8px; }
    `,
    autosave_interval: '30s',
    save_onsavecallback: function() { console.log('Content autosaved!'); },
    spellchecker_dialog: true,
    spellchecker_whitelist: ['TinyMCE', 'CEO', 'MyCompany']
});
</script>

<!-- Modern CSS -->
<style>
body { font-family: Arial, sans-serif; background: #f0f2f5; margin:0; padding:0; }
.container { max-width: 900px; margin: 50px 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: 30px; color:#333; }
form label { display:block; margin:15px 0 5px; font-weight:bold; color:#555; }
input[type="text"], input[type="file"], textarea { width:100%; padding:12px 15px; border:1px solid #ccc; border-radius:8px; box-sizing:border-box; margin-bottom:10px; }
button { padding:12px 25px; background:#004aad; color:#fff; border:none; border-radius:8px; cursor:pointer; font-size:16px; margin-top:10px; }
button:hover { background:#003a8c; }
img { margin-top:10px; border-radius:8px; border:1px solid #ccc; }
.success { color:green; margin-top:15px; font-weight:bold; }
@media(max-width:600px){ .container { margin:20px; padding:20px; } }
</style>
</head>
<body>

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

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

<label>About Text:</label>
<textarea name="about_text" class="tinymce"><?= htmlspecialchars($about['about_text']) ?></textarea>

<label>CEO Name:</label>
<input type="text" name="ceo_name" value="<?= htmlspecialchars($about['ceo_name']) ?>">

<label>CEO Message:</label>
<textarea name="ceo_message" class="tinymce"><?= htmlspecialchars($about['ceo_message']) ?></textarea>

<label>CEO Photo:</label>
<input type="file" name="ceo_photo">

<?php if(!empty($about['ceo_photo'])): ?>
<p>Current Photo:</p>
<img src="<?= $about['ceo_photo'] ?>" width="150">
<?php endif; ?>

<button type="submit">Save Changes</button>

<?php if(isset($success)) echo "<p class='success'>$success</p>"; ?>

</form>
</div>

</body>
</html>
