<?php
// Start session and include necessary files
session_start();
require_once '../config.php';
require_once '../includes/auth.php';
require_once '../classes/Slide.php';
require_once '../classes/User.php'; // Needed to get fkisp_id_of for slide creation/modification

// Redirect if not logged in or not a DAC Staff
redirect_if_not_logged_in('../index.php');
redirect_if_not_role('DAC Staff', '../index.php');

// Initialize Slide and User classes
$slideManager = new Slide($pdo);
$userManager = new User($pdo);

$action = $_GET['action'] ?? '';
$id = $_GET['id'] ?? null;

// Get current user's person ID for fkisp_id_of
$currentUserDetails = $userManager->getUserDetails($_SESSION['user_id']);
$fkisp_id_of = $currentUserDetails['fkisp_id_of'];

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action_type = $_POST['action_type'] ?? ''; // 'add' or 'edit' or 'delete'
    $title_en = trim($_POST['title_en'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $slide_id = $_POST['slide_id'] ?? null;
    $current_photo = $_POST['current_photo'] ?? ''; // For editing, keep track of existing photo

    if ($action_type === 'delete') {
        if ($slide_id) {
            try {
                $slideManager->deleteSlide($slide_id);
                set_message('Slide deleted successfully!', 'success');
            } catch (Exception $e) {
                set_message('Error deleting slide: ' . $e->getMessage(), 'danger');
            }
        }
    } else {
        // Handle photo upload
        $photoPath = $current_photo; // Default to current photo if not uploading new
        if (isset($_FILES['photo']) && $_FILES['photo']['error'] === UPLOAD_ERR_OK) {
            try {
                $photoPath = $slideManager->handlePhotoUpload($_FILES['photo']);
                // If editing and a new photo is uploaded, delete the old one
                if ($action_type === 'edit' && !empty($current_photo) && $current_photo !== $photoPath) {
                    // Ensure the old photo path is not empty and different from the new one
                    if (!empty($current_photo) && file_exists('../uploads/slides/' . $current_photo)) {
                        unlink('../uploads/slides/' . $current_photo); // Delete old file
                    }
                }
            } catch (Exception $e) {
                set_message('Photo upload error: ' . $e->getMessage(), 'danger');
                header('Location: manage_slides.php');
                exit();
            }
        } elseif ($action_type === 'add' && (!isset($_FILES['photo']) || $_FILES['photo']['error'] !== UPLOAD_ERR_OK)) {
            // For adding, a photo is required.
            set_message('Please upload a photo for the slide.', 'danger');
            header('Location: manage_slides.php');
            exit();
        }


        if (empty($title_en) || empty($description)) {
            set_message('Title and description cannot be empty.', 'danger');
        } else {
            try {
                if ($action_type === 'add') {
                    $slideManager->addSlide($title_en, $description, $photoPath, $_SESSION['user_id'], $fkisp_id_of);
                    set_message('Slide added successfully!', 'success');
                } elseif ($action_type === 'edit' && $slide_id) {
                    $slideManager->updateSlide($slide_id, $title_en, $description, $photoPath, $_SESSION['user_id'], $fkisp_id_of);
                    set_message('Slide updated successfully!', 'success');
                }
            } catch (Exception $e) {
                set_message('Error: ' . $e->getMessage(), 'danger');
            }
        }
    }
    header('Location: manage_slides.php');
    exit();
}

// Fetch slides for display
$slides = $slideManager->getAllSlides();

// Prepare data for editing if action is 'edit'
$editSlide = null;
if ($action === 'edit' && $id) {
    $editSlide = $slideManager->getSlideById($id);
}
?>

<!DOCTYPE html>
<html lang="en">
<!-- Header -->
<?php
// Include header file for admin pages
include_once("../includes/header_admin.php");
?>
<body>
    <div class="wrapper">
        <!-- Sidebar -->
        <?php
        // Include header file for admin pages
        include_once("../includes/nav_admin.php");
        ?>
        <!-- Main Content -->
        <div class="main-content">
            <nav class="navbar navbar-expand-lg navbar-light bg-light mb-4 rounded-3">
                <div class="container-fluid">
                    <a class="navbar-brand" href="#">Manage Slides</a>
                    <div class="d-flex">
                        <span class="navbar-text me-3">
                            Welcome, <?php echo htmlspecialchars($_SESSION['username']); ?>!
                        </span>
                    </div>
                </div>
            </nav>

            <?php
            // Display session messages
            if (isset($_SESSION['message'])) {
                echo '<div class="alert alert-' . $_SESSION['message_type'] . ' alert-dismissible fade show rounded" role="alert">' . htmlspecialchars($_SESSION['message']) . '<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button></div>';
                unset($_SESSION['message']);
                unset($_SESSION['message_type']);
            }
            ?>

            <div class="card mb-4">
                <div class="card-header bg-primary text-white">
                    <h5 class="mb-0"><?php echo $editSlide ? 'Edit' : 'Add New'; ?> Slide</h5>
                </div>
                <div class="card-body">
                    <form action="manage_slides.php" method="POST" enctype="multipart/form-data">
                        <input type="hidden" name="action_type" value="<?php echo $editSlide ? 'edit' : 'add'; ?>">
                        <?php if ($editSlide): ?>
                            <input type="hidden" name="slide_id" value="<?php echo htmlspecialchars($editSlide['pkdspsslide_id']); ?>">
                            <input type="hidden" name="current_photo" value="<?php echo htmlspecialchars($editSlide['dspsslide_photoname']); ?>">
                        <?php endif; ?>

                        <div class="mb-3">
                            <label for="title_en" class="form-label">Slide Title (English)</label>
                            <input type="text" class="form-control rounded" id="title_en" name="title_en" value="<?php echo htmlspecialchars($editSlide['dspsslide_title_en'] ?? ''); ?>" required>
                        </div>
                        <div class="mb-3">
                            <label for="description" class="form-label d-flex justify-content-between align-items-center">
                                <span>Description</span>
                            </label>
                            <textarea class="form-control rounded-3" id="description" name="description" rows="5" required><?php echo htmlspecialchars($editSlide['dspsslide_description'] ?? ''); ?></textarea>
                            <div class="form-text">Formatted text appears on the public carousel, so emphasise key phrases and provide concise summaries.</div>
                        </div>
                        <div class="mb-3">
                            <label for="photo" class="form-label">Slide Photo (JPG, PNG, GIF)</label>
                            <input type="file" class="form-control rounded" id="photo" name="photo" accept="image/*" <?php echo $editSlide ? '' : 'required'; ?>>
                            <?php if ($editSlide && !empty($editSlide['dspsslide_photoname'])): ?>
                                <div class="mt-2">
                                    Current Photo: <img src="../uploads/slides/<?php echo htmlspecialchars($editSlide['dspsslide_photoname']); ?>" alt="Slide Photo" class="slide-img-thumbnail">
                                </div>
                            <?php endif; ?>
                        </div>
                        <button type="submit" class="btn btn-primary rounded">
                            <i class="fas fa-<?php echo $editSlide ? 'save' : 'plus'; ?> me-2"></i> <?php echo $editSlide ? 'Update' : 'Add'; ?> Slide
                        </button>
                        <?php if ($editSlide): ?>
                            <a href="manage_slides.php" class="btn btn-secondary rounded ms-2">Cancel Edit</a>
                        <?php endif; ?>
                    </form>
                </div>
            </div>

            <div class="card">
                <div class="card-header text-white" style="background-color: #28a745;">
                    <h5 class="mb-0">All Slides</h5>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover table-striped">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>Title</th>
                                    <th>Description</th>
                                    <th>Photo</th>
                                    <th>Reg. Date</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (!empty($slides)): ?>
                                    <?php foreach ($slides as $slide): ?>
                                        <tr>
                                            <td><?php echo htmlspecialchars($slide['pkdspsslide_id']); ?></td>
                                            <td><?php echo htmlspecialchars($slide['dspsslide_title_en']); ?></td>
                                            <td><?php echo htmlspecialchars(substr($slide['dspsslide_description'], 0, 100)) . (strlen($slide['dspsslide_description']) > 100 ? '...' : ''); ?></td>
                                            <td>
                                                <?php if (!empty($slide['dspsslide_photoname'])): ?>
                                                    <img src="../uploads/slides/<?php echo htmlspecialchars($slide['dspsslide_photoname']); ?>" alt="Slide Photo" class="slide-img-thumbnail">
                                                <?php else: ?>
                                                    N/A
                                                <?php endif; ?>
                                            </td>
                                            <td><?php echo htmlspecialchars($slide['dspsslide_reg_datetime']); ?></td>
                                            <td>
                                                <a href="manage_slides.php?action=edit&id=<?php echo htmlspecialchars($slide['pkdspsslide_id']); ?>" class="btn btn-sm btn-warning rounded btn-action">
                                                    <i class="fas fa-edit"></i>
                                                </a>
                                                <form action="manage_slides.php" method="POST" class="d-inline" onsubmit="return confirm('Are you sure you want to delete this slide? This action cannot be undone.');">
                                                    <input type="hidden" name="action_type" value="delete">
                                                    <input type="hidden" name="slide_id" value="<?php echo htmlspecialchars($slide['pkdspsslide_id']); ?>">
                                                    <button type="submit" class="btn btn-sm btn-danger rounded btn-action">
                                                        <i class="fas fa-trash-alt"></i>
                                                    </button>
                                                </form>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php else: ?>
                                    <tr>
                                        <td colspan="6" class="text-center">No slides found.</td>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Footer -->
<?php
// Include Footer file for owner pages
include_once("../includes/footer_admin.php");
?>   
    <script src="https://cdn.jsdelivr.net/npm/@ckeditor/ckeditor5-build-classic@38.1.1/build/ckeditor.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function () {
            var textarea = document.querySelector('#description');
            if (textarea && typeof ClassicEditor !== 'undefined') {
                ClassicEditor
                    .create(textarea, {
                        toolbar: [
                            'heading','|','bold','italic','underline','bulletedList','numberedList','blockQuote',
                            '|','link','insertTable','undo','redo'
                        ]
                    })
                    .catch(function (error) {
                        console.error('Failed to initialise rich text editor', error);
                    });
            }
        });
    </script>
</body>
</html>
