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

session_start();

/* ================= Session Timeout (12 hours) ================= */
$SESSION_TIMEOUT = 43200;

if (isset($_SESSION['LAST_ACTIVITY'])) {
    if (time() - $_SESSION['LAST_ACTIVITY'] > $SESSION_TIMEOUT) {
        session_unset();
        session_destroy();
        header("Location: login.php?timeout=1");
        exit;
    }
}
$_SESSION['LAST_ACTIVITY'] = time();

include('includes/db.php');
include('includes/header.php');

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

// ---------------- Handle CRUD ----------------
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // DEBUG: Check what's being posted
    error_log("POST Data: " . print_r($_POST, true));
    error_log("FILES Data: " . print_r($_FILES, true));

    if (!isset($_POST['csrf']) || $_POST['csrf'] !== $_SESSION['csrf_token']) {
        die("Invalid CSRF token");
    }

    // ---------- CREATE ----------
    if (isset($_POST['create'])) {
        $title = trim($_POST['title']);
        $description = trim($_POST['description']);
        $detail = trim($_POST['detail']);
        
        // Handle image upload
        $image_path = '';
        if (isset($_FILES['image']) && $_FILES['image']['error'] == 0) {
            $allowed_types = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
            $file_type = $_FILES['image']['type'];
            
            if (in_array($file_type, $allowed_types)) {
                $upload_dir = 'assets/img/services/';
                if (!is_dir($upload_dir)) {
                    mkdir($upload_dir, 0777, true);
                }
                
                $file_ext = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
                $file_name = 'service_' . time() . '_' . rand(1000, 9999) . '.' . $file_ext;
                $file_path = $upload_dir . $file_name;
                
                if (move_uploaded_file($_FILES['image']['tmp_name'], $file_path)) {
                    $image_path = $file_path;
                }
            }
        }

        $stmt = $pdo->prepare("INSERT INTO services (title, description, detail, image_path, status) VALUES (?, ?, ?, ?, 'enabled')");
        if ($stmt->execute([$title, $description, $detail, $image_path])) {
            $_SESSION['flash'] = ['message'=>'Service added successfully!','color'=>'#28a745'];
        } else {
            $_SESSION['flash'] = ['message'=>'Failed to add service.','color'=>'#dc3545'];
        }
        header("Location: ".$_SERVER['PHP_SELF']);
        exit;
    }

    // ---------- UPDATE ----------
    if (isset($_POST['update'])) {
        $id = intval($_POST['id']);
        $title = trim($_POST['title']);
        $description = trim($_POST['description']);
        $detail = trim($_POST['detail']);
        
        // Handle image update
        $image_path = null;
        if (isset($_FILES['image']) && $_FILES['image']['error'] == 0) {
            $allowed_types = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
            $file_type = $_FILES['image']['type'];
            
            if (in_array($file_type, $allowed_types)) {
                $upload_dir = 'assets/img/services/';
                if (!is_dir($upload_dir)) {
                    mkdir($upload_dir, 0777, true);
                }
                
                $file_ext = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
                $file_name = 'service_' . time() . '_' . rand(1000, 9999) . '.' . $file_ext;
                $file_path = $upload_dir . $file_name;
                
                if (move_uploaded_file($_FILES['image']['tmp_name'], $file_path)) {
                    $image_path = $file_path;
                }
            }
        }

        if ($image_path) {
            // Update with new image
            $stmt = $pdo->prepare("UPDATE services SET title=?, description=?, detail=?, image_path=? WHERE id=?");
            $result = $stmt->execute([$title, $description, $detail, $image_path, $id]);
        } else {
            // Update without changing image
            $stmt = $pdo->prepare("UPDATE services SET title=?, description=?, detail=? WHERE id=?");
            $result = $stmt->execute([$title, $description, $detail, $id]);
        }
        
        if ($result) {
            $_SESSION['flash'] = ['message'=>'Service updated successfully!','color'=>'#007bff'];
        } else {
            $_SESSION['flash'] = ['message'=>'Failed to update service.','color'=>'#dc3545'];
        }
        header("Location: ".$_SERVER['PHP_SELF']);
        exit;
    }

    // ---------- TOGGLE ENABLE/DISABLE ----------
    if (isset($_POST['toggle'])) {
        $id = intval($_POST['id']);
        $currentStatus = $_POST['current_status'] === 'enabled' ? 'disabled' : 'enabled';

        $stmt = $pdo->prepare("UPDATE services SET status=? WHERE id=?");
        if ($stmt->execute([$currentStatus, $id])) {
            $statusText = $currentStatus=='enabled' ? 'Service enabled!' : 'Service disabled!';
            $statusColor = $currentStatus=='enabled' ? '#28a745' : '#dc3545';
            $_SESSION['flash'] = ['message'=>$statusText,'color'=>$statusColor];
        } else {
            $_SESSION['flash'] = ['message'=>'Failed to update status.','color'=>'#dc3545'];
        }
        header("Location: ".$_SERVER['PHP_SELF']);
        exit;
    }
    
    // ---------- DELETE ----------
    if (isset($_POST['delete'])) {
        $id = intval($_POST['id']);
        
        // Get image path first to delete the file
        $stmt = $pdo->prepare("SELECT image_path FROM services WHERE id = ?");
        $stmt->execute([$id]);
        $service = $stmt->fetch(PDO::FETCH_ASSOC);
        
        // Delete the record
        $stmt = $pdo->prepare("DELETE FROM services WHERE id = ?");
        if ($stmt->execute([$id])) {
            // Delete the image file if exists
            if ($service && !empty($service['image_path']) && file_exists($service['image_path'])) {
                unlink($service['image_path']);
            }
            $_SESSION['flash'] = ['message'=>'Service deleted successfully!','color'=>'#dc3545'];
        } else {
            $_SESSION['flash'] = ['message'=>'Failed to delete service.','color'=>'#dc3545'];
        }
        header("Location: ".$_SERVER['PHP_SELF']);
        exit;
    }
}

// ---------------- Fetch Services ----------------
$servicesStmt = $pdo->query("
    SELECT *
    FROM services
    ORDER BY id DESC
");
$services = $servicesStmt->fetchAll(PDO::FETCH_ASSOC);
?>

<!-- Add TinyMCE CSS and JS links in the head section -->
<!-- We'll add this via PHP in the header, but for now let's add it directly -->
<link rel="stylesheet" href="assets/tinymce/skins/ui/oxide/skin.min.css">
<script src="assets/tinymce/tinymce.min.js"></script>

<!-- 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>

<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">Services Management</h4>
        </div>
        <div class="card-body collapse in">
          <div class="card-block card-dashboard">
            <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="#addServiceModal">Add Service</button>
              </div>
            </div>

            <div class="table-responsive">
              <table class="table table-hover mb-0" id="Table">
                <thead>
                  <tr>
                    <th>#</th>
                    <th>Image</th>
                    <th>Title</th>
                    <th>Description</th>
                    <th>Status</th>
                    <th>Actions</th>
                  </tr>
                </thead>
                <tbody>
                  <?php $counter=1; foreach($services as $service): ?>
                  <tr>
                    <td><?= $counter++ ?></td>
                    <td>
                      <?php if (!empty($service['image_path'])): ?>
                        <img src="<?= $service['image_path'] ?>" alt="<?= htmlspecialchars($service['title']) ?>" 
                             style="width: 60px; height: 45px; object-fit: cover; border-radius: 4px;">
                      <?php else: ?>
                        <span class="text-muted">No Image</span>
                      <?php endif; ?>
                    </td>
                    <td><?= htmlspecialchars($service['title']) ?></td>
                    <td><?= htmlspecialchars(substr(strip_tags($service['description']), 0, 50)) . (strlen(strip_tags($service['description'])) > 50 ? '...' : '') ?></td>
                    <td style="color: <?= $service['status']=='enabled'?'#28a745':'#dc3545' ?>; font-weight:bold;">
                        <?= ucfirst($service['status']) ?>
                    </td>
                    <td>
                      <button class="btn btn-sm btn-primary" data-toggle="modal" data-target="#editModal<?= $service['id'] ?>">Edit</button>
                      
                      <button class="btn btn-sm btn-info" data-toggle="modal" data-target="#viewModal<?= $service['id'] ?>">View</button>

                      <form method="post" style="display:inline-block">
                        <input type="hidden" name="id" value="<?= $service['id'] ?>">
                        <input type="hidden" name="current_status" value="<?= $service['status'] ?>">
                        <input type="hidden" name="csrf" value="<?= $csrf ?>">
                        <button type="submit" name="toggle" class="btn btn-sm <?= $service['status']=='enabled'?'btn-secondary':'btn-success' ?>">
                          <?= $service['status']=='enabled'?'Disable':'Enable' ?>
                        </button>
                      </form>
                      
                      <form method="post" style="display:inline-block">
                        <input type="hidden" name="id" value="<?= $service['id'] ?>">
                        <input type="hidden" name="csrf" value="<?= $csrf ?>">
                        <button type="submit" name="delete" class="btn btn-sm btn-danger" 
                                onclick="return confirm('Are you sure you want to delete this service?')">Delete</button>
                      </form>
                    </td>
                  </tr>
                  <?php endforeach; ?>
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- Add Service Modal -->
<div class="modal fade" id="addServiceModal" 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">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <label class="modal-title">Add New Service</label>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <label>Title *</label>
            <input type="text" name="title" class="form-control" placeholder="Enter service title" required>
          </div>
          
          <div class="form-group">
            <label>Description *</label>
            <textarea name="description" class="form-control" rows="3" placeholder="Enter service description" required></textarea>
          </div>
          
          <div class="form-group">
            <label>Detail *</label>
            <textarea id="detailAdd" name="detail" class="form-control" rows="10" placeholder="Enter full service details" required></textarea>
          </div>
          
          <div class="form-group">
            <label>Image</label>
            <input type="file" name="image" class="form-control-file" accept="image/*">
            <small class="text-muted">Optional: Upload service image (JPG, PNG, GIF, WebP)</small>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-outline-secondary btn-md" data-dismiss="modal">Close</button>
          <button type="submit" name="create" class="btn btn-outline-primary btn-md">Save</button>
        </div>
      </form>
    </div>
  </div>
</div>

<!-- MODALS MUST BE OUTSIDE THE TABLE/TBODY -->
<?php foreach($services as $service): ?>
<!-- View Modal -->
<div class="modal fade" id="viewModal<?= $service['id'] ?>" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h4>Service Details</h4>
        <button type="button" class="close" data-dismiss="modal">&times;</button>
      </div>
      <div class="modal-body">
        <?php if (!empty($service['image_path'])): ?>
          <div class="text-center mb-3">
            <img src="<?= $service['image_path'] ?>" alt="<?= htmlspecialchars($service['title']) ?>" 
                 class="img-fluid" style="max-height: 300px;">
          </div>
        <?php endif; ?>
        
        <h5><?= htmlspecialchars($service['title']) ?></h5>
        <p><strong>Description:</strong></p>
        <p><?= nl2br(htmlspecialchars($service['description'])) ?></p>
        <p><strong>Detail:</strong></p>
        <div class="border p-3 bg-light">
          <?= $service['detail'] ?>
        </div>
        
        <p class="text-muted mt-3">
          <small>Status: <?= ucfirst($service['status']) ?></small><br>
          <small>Created: <?= date('Y-m-d H:i', strtotime($service['created_at'])) ?></small>
        </p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-outline-secondary btn-md" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

<!-- Edit Modal -->
<div class="modal fade" id="editModal<?= $service['id'] ?>" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <form method="post" enctype="multipart/form-data">
        <input type="hidden" name="csrf" value="<?= $csrf ?>">
        <input type="hidden" name="id" value="<?= $service['id'] ?>">

        <div class="modal-header">
          <h4>Edit Service</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" value="<?= htmlspecialchars($service['title']) ?>" required>
          </div>
          
          <div class="form-group">
            <label>Description *</label>
            <textarea name="description" class="form-control" rows="3" required><?= htmlspecialchars($service['description']) ?></textarea>
          </div>
          
          <div class="form-group">
            <label>Detail *</label>
            <textarea id="detailEdit<?= $service['id'] ?>" name="detail" class="form-control tinymce-editor" rows="10" required><?= htmlspecialchars($service['detail']) ?></textarea>
          </div>
          
          <div class="form-group">
            <label>Image</label>
            <?php if (!empty($service['image_path'])): ?>
              <div class="mb-2">
                <img src="<?= $service['image_path'] ?>" alt="Current Image" 
                     style="max-width: 150px; max-height: 100px; border-radius: 4px;" class="img-thumbnail">
                <br>
                <small class="text-muted">Current image</small>
              </div>
            <?php endif; ?>
            <input type="file" name="image" class="form-control-file" accept="image/*">
            <small class="text-muted">Upload new image to replace current one</small>
          </div>
          
          <div class="form-group">
            <label>Status</label>
            <select class="form-control" disabled>
              <option><?= ucfirst($service['status']) ?></option>
            </select>
            <small class="text-muted">Use Enable/Disable button to change status</small>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-outline-secondary btn-md" data-dismiss="modal">Close</button>
          <button type="submit" name="update" class="btn btn-outline-primary btn-md">Update</button>
        </div>
      </form>
    </div>
  </div>
</div>
<?php endforeach; ?>

<style>
.toast-message{
  position:fixed;
  top:20px;
  right:20px;
  z-index:9999;
  padding:.75rem 1rem;
  border-radius:.25rem;
  opacity:0.95;
  color: #fff;
  font-weight: 600;
  box-shadow: 0 2px 6px rgba(0,0,0,0.2);
}

.img-thumbnail {
  border: 1px solid #ddd;
}

/* Fix modal backdrop */
.modal-backdrop {
  z-index: 1040 !important;
}
.modal {
  z-index: 1050 !important;
}

/* TinyMCE adjustments for modals */
.tox-tinymce {
  border: 1px solid #ddd !important;
  border-radius: 4px !important;
}
</style>

<script>
// Initialize TinyMCE for modals
function initTinyMCE(selector) {
    if (typeof tinymce !== 'undefined') {
        // Remove existing editor instance if any
        tinymce.remove(selector);
        
        // Initialize new editor
        tinymce.init({
            selector: selector,
            height: 300,
            menubar: false,
            plugins: [
                'advlist autolink lists link image charmap print preview anchor',
                'searchreplace visualblocks code fullscreen',
                'insertdatetime media table paste code help wordcount'
            ],
            toolbar: 'undo redo | formatselect | bold italic backcolor | \
                      alignleft aligncenter alignright alignjustify | \
                      bullist numlist outdent indent | removeformat | help',
            content_style: 'body { font-family:Helvetica,Arial,sans-serif; font-size:14px }',
            setup: function (editor) {
                editor.on('change', function () {
                    editor.save();
                });
            }
        });
    } else {
        console.error('TinyMCE not loaded');
    }
}

// Initialize TinyMCE when modals are shown
$(document).ready(function() {
    // Initialize TinyMCE for add modal
    $('#addServiceModal').on('shown.bs.modal', function () {
        initTinyMCE('#detailAdd');
    });
    
    // Initialize TinyMCE for each edit modal
    <?php foreach($services as $service): ?>
    $('#editModal<?= $service['id'] ?>').on('shown.bs.modal', function () {
        initTinyMCE('#detailEdit<?= $service['id'] ?>');
    });
    
    // Destroy TinyMCE when modal is hidden
    $('#editModal<?= $service['id'] ?>').on('hidden.bs.modal', function () {
        if (typeof tinymce !== 'undefined') {
            tinymce.remove('#detailEdit<?= $service['id'] ?>');
        }
    });
    <?php endforeach; ?>
    
    // Destroy TinyMCE for add modal when hidden
    $('#addServiceModal').on('hidden.bs.modal', function () {
        if (typeof tinymce !== 'undefined') {
            tinymce.remove('#detailAdd');
        }
    });
});

// Debug function to check if modals are working
document.addEventListener('DOMContentLoaded', function() {
  console.log('DOM loaded');
  
  // Check if TinyMCE is loaded
  if (typeof tinymce !== 'undefined') {
    console.log('TinyMCE is loaded');
  } else {
    console.error('TinyMCE is NOT loaded');
  }
  
  // Check if Bootstrap is loaded
  if (typeof $ === 'function') {
    console.log('jQuery is loaded');
  }
});
</script>

<?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; ?>