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

include('includes/db.php');
include('includes/header.php'); // Navbar and CSS

// ---------------- CSRF Token ----------------
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
$csrf = $_SESSION['csrf_token'];

// ---------------- Fetch existing content BEFORE handling POST ----------------
$stmt = $pdo->prepare("SELECT * FROM page_content WHERE page='about' LIMIT 1");
$stmt->execute();
$existing_content = $stmt->fetch(PDO::FETCH_ASSOC);

// ---------------- Handle POST ----------------
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_POST['csrf']) || $_POST['csrf'] !== $_SESSION['csrf_token']) {
        die("Invalid CSRF token");
    }

    $title = trim($_POST['title']);
    $description = trim($_POST['description']);
    $detail = trim($_POST['detail']);
    $aim = trim($_POST['aim']);
    $vision = trim($_POST['vision']);
    $mission = trim($_POST['mission']);
    $objectives = trim($_POST['objectives']);
    $core_values = trim($_POST['core_values']);

    // Initialize image paths with existing values
    $image_1 = $existing_content['image_1'] ?? null;
    $image_2 = $existing_content['image_2'] ?? null;
    $image_3 = $existing_content['image_3'] ?? null;

    // Handle 3 images - only update if new file is uploaded
    $upload_dir = 'asset/img/';
    if (!is_dir($upload_dir)) mkdir($upload_dir, 0777, true);

    for ($i = 1; $i <= 3; $i++) {
        $file_key = "image_$i";
        if (isset($_FILES[$file_key]) && $_FILES[$file_key]['error'] == 0 && $_FILES[$file_key]['size'] > 0) {
            $allowed_types = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
            if (in_array($_FILES[$file_key]['type'], $allowed_types)) {
                $ext = pathinfo($_FILES[$file_key]['name'], PATHINFO_EXTENSION);
                $filename = "about_{$i}_" . time() . '.' . $ext;
                $filepath = $upload_dir . $filename;
                
                if (move_uploaded_file($_FILES[$file_key]['tmp_name'], $filepath)) {
                    // Delete old image if it exists
                    $old_image_field = "image_$i";
                    if (!empty($existing_content[$old_image_field]) && file_exists($existing_content[$old_image_field])) {
                        unlink($existing_content[$old_image_field]);
                    }
                    
                    // Set new image path
                    ${"image_$i"} = $filepath;
                }
            }
        }
    }

    if ($existing_content) {
        // Update existing record
        $stmt = $pdo->prepare("
            UPDATE page_content SET 
            title = ?, 
            description = ?, 
            detail = ?, 
            aim = ?, 
            vision = ?, 
            mission = ?, 
            objectives = ?, 
            core_values = ?, 
            image_1 = ?, 
            image_2 = ?, 
            image_3 = ? 
            WHERE page = 'about'
        ");
        
        $stmt->execute([
            $title,
            $description,
            $detail,
            $aim,
            $vision,
            $mission,
            $objectives,
            $core_values,
            $image_1,
            $image_2,
            $image_3
        ]);
        
        $_SESSION['flash'] = ['message' => 'About page updated successfully!', 'color' => '#007bff'];
    } else {
        // Insert new record
        $stmt = $pdo->prepare("
            INSERT INTO page_content 
            (page, title, description, detail, aim, vision, mission, objectives, core_values, image_1, image_2, image_3)
            VALUES ('about', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        ");
        
        $stmt->execute([
            $title,
            $description,
            $detail,
            $aim,
            $vision,
            $mission,
            $objectives,
            $core_values,
            $image_1,
            $image_2,
            $image_3
        ]);
        
        $_SESSION['flash'] = ['message' => 'About page created successfully!', 'color' => '#28a745'];
    }

    header("Location: " . $_SERVER['PHP_SELF']);
    exit;
}

// ---------------- Fetch About Page for display ----------------
$stmt = $pdo->prepare("SELECT * FROM page_content WHERE page='about' LIMIT 1");
$stmt->execute();
$content = $stmt->fetch(PDO::FETCH_ASSOC);
?>
<!-- Navbar and Sidebar -->
<nav class="header-navbar navbar navbar-with-menu navbar-fixed-top navbar-semi-dark navbar-shadow">
  <?php include('includes/navbar.php'); ?>
</nav>
<div class="main-menu menu-fixed menu-dark menu-accordion menu-shadow">
  <?php include('includes/sidebar.php'); ?>
</div>
<!-- Main Content -->
<div class="app-content content container-fluid">
  <div class="content-wrapper">
    <div class="col-xs-12">
      <div class="card">
        <div class="card-header">
          <h4 class="card-title">About Page Management</h4>
        </div>
        <div class="card-body collapse in">
          <div class="card-block card-dashboard">

            <!-- Edit Button -->
            <div class="row mb-2">
              <div class="col-lg-4 col-md-6 col-sm-12">
                <button type="button" class="btn btn-outline-primary btn-md" data-toggle="modal" data-target="#editAboutModal">
                    Edit About Page
                </button>
              </div>
            </div>

            <!-- Table -->
            <div class="table-responsive">
              <table class="table table-hover mb-0" id="Table">
                <thead>
                  <tr>
                    <th>#</th>
                    <th>Title</th>
                    <th>Description</th>
                    <th>Images</th>
                    <th>Aim</th>
                    <th>Vision</th>
                    <th>Mission</th>
                    <th>Objectives</th>
                    <th>Core Values</th>
                    <th>Actions</th>
                  </tr>
                </thead>
                <tbody>
                  <tr>
                    <td>1</td>
                    <td><?= htmlspecialchars($content['title'] ?? '') ?></td>
                    <td>
                        <?= htmlspecialchars(substr(strip_tags($content['description'] ?? ''),0,50)) ?>...
                        <button class="btn btn-sm btn-info" data-toggle="modal" data-target="#viewDescModal">View More</button>
                    </td>
                    <td>
                        <?php for($i=1;$i<=3;$i++): ?>
                          <?php if(!empty($content["image_$i"])): ?>
                            <img src="<?= htmlspecialchars($content["image_$i"]) ?>" style="width:50px;height:40px;object-fit:cover;margin-right:5px;border-radius:4px;">
                          <?php endif; ?>
                        <?php endfor; ?>
                    </td>
                    <td><?= htmlspecialchars(substr($content['aim'] ?? '',0,30)) ?>...</td>
                    <td><?= htmlspecialchars(substr($content['vision'] ?? '',0,30)) ?>...</td>
                    <td><?= htmlspecialchars(substr($content['mission'] ?? '',0,30)) ?>...</td>
                    <td><?= htmlspecialchars(substr($content['objectives'] ?? '',0,30)) ?>...</td>
                    <td><?= htmlspecialchars(substr($content['core_values'] ?? '',0,30)) ?>...</td>
                    <td>
                      <button class="btn btn-sm btn-primary" data-toggle="modal" data-target="#editAboutModal">Edit</button>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>

          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- View Description Modal -->
<div class="modal fade" id="viewDescModal" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h4>About Page Full Description</h4>
        <button type="button" class="close" data-dismiss="modal">&times;</button>
      </div>
      <div class="modal-body">
        <p><strong>Description:</strong></p>
        <p><?= nl2br(htmlspecialchars($content['description'] ?? '')) ?></p>
        <p><strong>Detail:</strong></p>
        <p><?= nl2br(htmlspecialchars($content['detail'] ?? '')) ?></p>
        <p><strong>Aim:</strong> <?= nl2br(htmlspecialchars($content['aim'] ?? '')) ?></p>
        <p><strong>Vision:</strong> <?= nl2br(htmlspecialchars($content['vision'] ?? '')) ?></p>
        <p><strong>Mission:</strong> <?= nl2br(htmlspecialchars($content['mission'] ?? '')) ?></p>
        <p><strong>Objectives:</strong> <?= nl2br(htmlspecialchars($content['objectives'] ?? '')) ?></p>
        <p><strong>Core Values:</strong> <?= nl2br(htmlspecialchars($content['core_values'] ?? '')) ?></p>
      </div>
      <div class="modal-footer">
        <button class="btn btn-outline-secondary btn-md" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

<!-- Edit Modal -->
<div class="modal fade" id="editAboutModal" tabindex="-1" role="dialog">
  <div class="modal-dialog modal-lg" role="document">
    <div class="modal-content">
      <form method="post" enctype="multipart/form-data">
        <input type="hidden" name="csrf" value="<?= $csrf ?>">
        <div class="modal-header">
          <h4 class="modal-title">Edit About Page</h4>
          <button type="button" class="close" data-dismiss="modal">&times;</button>
        </div>
        <div class="modal-body">

          <div class="form-group">
            <label>Title *</label>
            <input type="text" name="title" class="form-control" required value="<?= htmlspecialchars($content['title'] ?? '') ?>">
          </div>

          <div class="form-group">
            <label>Description *</label>
            <textarea name="description" class="form-control" rows="3" required><?= htmlspecialchars($content['description'] ?? '') ?></textarea>
          </div>

          <div class="form-group">
            <label>Detail *</label>
            <textarea name="detail" class="form-control" rows="4" required><?= htmlspecialchars($content['detail'] ?? '') ?></textarea>
          </div>

          <div class="form-group">
            <label>Aim</label>
            <textarea name="aim" class="form-control"><?= htmlspecialchars($content['aim'] ?? '') ?></textarea>
          </div>
          
          <div class="form-group">
            <label>Vision</label>
            <textarea name="vision" class="form-control"><?= htmlspecialchars($content['vision'] ?? '') ?></textarea>
          </div>
          
          <div class="form-group">
            <label>Mission</label>
            <textarea name="mission" class="form-control"><?= htmlspecialchars($content['mission'] ?? '') ?></textarea>
          </div>
          
          <div class="form-group">
            <label>Objectives</label>
            <textarea name="objectives" class="form-control"><?= htmlspecialchars($content['objectives'] ?? '') ?></textarea>
          </div>
          
          <div class="form-group">
            <label>Core Values</label>
            <textarea name="core_values" class="form-control"><?= htmlspecialchars($content['core_values'] ?? '') ?></textarea>
          </div>

          <?php for($i=1;$i<=3;$i++): ?>
          <div class="form-group">
            <label>Image <?= $i ?> (Leave empty to keep current)</label><br>
            <?php if(!empty($content["image_$i"])): ?>
              <div class="current-image mb-2">
                <strong>Current:</strong><br>
                <img src="<?= htmlspecialchars($content["image_$i"]) ?>" style="max-width:150px;margin-bottom:5px;border:1px solid #ddd;padding:3px;">
              </div>
            <?php endif; ?>
            <input type="file" name="image_<?= $i ?>" accept="image/*" class="form-control-file">
          </div>
          <?php endfor; ?>

        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-outline-secondary btn-md" data-dismiss="modal">Close</button>
          <button type="submit" class="btn btn-outline-primary btn-md">Save Changes</button>
        </div>
      </form>
    </div>
  </div>
</div>

<?php include('includes/footer.php'); ?>

<?php if(isset($_SESSION['flash'])): ?>
<script>
  window.onload=function(){
    const toast=document.createElement('div');
    toast.className='toast-message';
    toast.style.background='<?= $_SESSION['flash']['color'] ?>';
    toast.innerText='<?= $_SESSION['flash']['message'] ?>';
    document.body.appendChild(toast);
    setTimeout(()=>toast.remove(),4000);
  }
</script>
<?php unset($_SESSION['flash']); endif; ?>