<?php
// Start session and include necessary files
session_start();
require_once '../config.php';
require_once '../includes/auth.php';
require_once '../classes/Aboutus.php';
require_once '../classes/User.php'; // To get person_id for the Aboutus class

// 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 Aboutus class
$aboutUs = new Aboutus($pdo);
$user = new User($pdo); // To get the person_id of the logged-in user

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

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action_type = $_POST['action_type'] ?? ''; // 'add' or 'edit' or 'delete'
    $title = trim($_POST['title'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $about_id = $_POST['about_id'] ?? null;

    // Get the person_id of the currently logged-in user
    $currentUserDetails = $user->getUserDetails($_SESSION['user_id']);
    $fkisp_id_of = $currentUserDetails['fkisp_id_of'];

    if ($action_type === 'delete') {
        if ($about_id) {
            try {
                $aboutUs->deleteAboutUs($about_id);
                set_message('About Us entry deleted successfully!', 'success');
            } catch (Exception $e) {
                set_message('Error deleting About Us entry: ' . $e->getMessage(), 'danger');
            }
        }
    } else {
        if (empty($title) || empty($description)) {
            set_message('Title and description cannot be empty.', 'danger');
        } else {
            try {
                if ($action_type === 'add') {
                    $aboutUs->addAboutUs($title, $description, $_SESSION['user_id'], $fkisp_id_of);
                    set_message('About Us entry added successfully!', 'success');
                } elseif ($action_type === 'edit' && $about_id) {
                    $aboutUs->updateAboutUs($about_id, $title, $description, $_SESSION['user_id'], $fkisp_id_of);
                    set_message('About Us entry updated successfully!', 'success');
                }
            } catch (Exception $e) {
                set_message('Error: ' . $e->getMessage(), 'danger');
            }
        }
    }
    header('Location: manage_aboutus.php');
    exit();
}

// Fetch About Us entries for display
$aboutUsEntries = $aboutUs->getAllAboutUs();

// Prepare data for editing if action is 'edit'
$editAboutUs = null;
if ($action === 'edit' && $id) {
    $editAboutUs = $aboutUs->getAboutUsById($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 About Us</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 $editAboutUs ? 'Edit' : 'Add New'; ?> About Us Entry</h5>
                </div>
                <div class="card-body">
                    <form action="manage_aboutus.php" method="POST">
                        <input type="hidden" name="action_type" value="<?php echo $editAboutUs ? 'edit' : 'add'; ?>">
                        <?php if ($editAboutUs): ?>
                            <input type="hidden" name="about_id" value="<?php echo htmlspecialchars($editAboutUs['pkdspsabout_id']); ?>">
                        <?php endif; ?>

                        <div class="mb-3">
                            <label for="title" class="form-label">Title</label>
                            <input type="text" class="form-control rounded" id="title" name="title" value="<?php echo htmlspecialchars($editAboutUs['dspsabout_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="8" required><?php echo htmlspecialchars($editAboutUs['dspsabout_description'] ?? ''); ?></textarea>
                            <div class="form-text">Format paragraphs, bullet lists, and links so the public About Us page is easy to read.</div>
                        </div>
                        <button type="submit" class="btn btn-primary rounded">
                            <i class="fas fa-<?php echo $editAboutUs ? 'save' : 'plus'; ?> me-2"></i> <?php echo $editAboutUs ? 'Update' : 'Add'; ?> Entry
                        </button>
                        <?php if ($editAboutUs): ?>
                            <a href="manage_aboutus.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 About Us Entries</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>Reg. Date</th>
                                    <th>Mod. Date</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (!empty($aboutUsEntries)): ?>
                                    <?php foreach ($aboutUsEntries as $entry): ?>
                                        <tr>
                                            <td><?php echo htmlspecialchars($entry['pkdspsabout_id']); ?></td>
                                            <td><?php echo htmlspecialchars($entry['dspsabout_title_en']); ?></td>
                                            <td><?php echo htmlspecialchars(substr($entry['dspsabout_description'], 0, 100)) . (strlen($entry['dspsabout_description']) > 100 ? '...' : ''); ?></td>
                                            <td><?php echo htmlspecialchars($entry['dspsabout_reg_datetime']); ?></td>
                                            <td><?php echo htmlspecialchars($entry['dspsabout_mod_datetime']); ?></td>
                                            <td>
                                                <a href="manage_aboutus.php?action=edit&id=<?php echo htmlspecialchars($entry['pkdspsabout_id']); ?>" class="btn btn-sm btn-warning rounded btn-action">
                                                    <i class="fas fa-edit"></i>
                                                </a>
                                                <form action="manage_aboutus.php" method="POST" class="d-inline" onsubmit="return confirm('Are you sure you want to delete this About Us entry?');">
                                                    <input type="hidden" name="action_type" value="delete">
                                                    <input type="hidden" name="about_id" value="<?php echo htmlspecialchars($entry['pkdspsabout_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 About Us entries 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>
