<?php
session_start();
error_reporting(0);
include('includes/config.php');

if (strlen($_SESSION['alogin']) == 0) {
    header('location:index.php');
    exit;
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Theme | Online Library</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- <link rel="icon" type="image/x-icon" href="../<?php echo htmlentities($_SESSION['logo']); ?>"> -->
    <link rel="icon" type="image/x-icon" href="../<?php echo htmlentities($_SESSION['logo']); ?>?v=<?php echo time(); ?>">


    <!-- Bootstrap 5 -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">

    <!-- DataTables Bootstrap 5 -->
    <link href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css" rel="stylesheet">

    <!-- FontAwesome -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">

    <style>
        .square-card {
            width: 100%;
            background-color: #f8f9fa;
            border: 1px solid #dee2e6;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.05);
            border-radius: 5px;
        }

        .flash-message {
            max-width: 600px;
            margin: 0 auto 15px;
        }

        .table-wrapper {
            overflow-x: auto;
            padding: 10px;
        }

        .col-md-12 h5 {
            color:   #0d6efd;
            font-size: 20px;
        }

        .btn+.btn {
            margin-left: 5px;
        }
    </style>
</head>

<body>
    <div class="d-flex flex-column min-vh-100">
        <?php include('includes/header.php'); ?>

        <div class="main-content flex-grow-1">
            <div class="row pad-botm mb-4">
                <div class="col-md-12">
                    <h5 class="header-line" style="color:#0d6efd;">THEME SETTINGS</h5>
                </div>
            </div>

            <!-- Flash Messages -->
            <div class="row justify-content-center">
                <div class="col-md-8">
                    <?php foreach (['error', 'msg', 'updatemsg', 'delmsg'] as $type): ?>
                        <?php if (!empty($_SESSION[$type])): ?>
                            <div class="alert alert-<?php echo ($type == 'error') ? 'danger' : 'success'; ?> flash-message">
                                <strong><?php echo ucfirst($type); ?> :</strong> <?php echo htmlentities($_SESSION[$type]); ?>
                                <?php $_SESSION[$type] = ""; ?>
                            </div>
                        <?php endif; ?>
                    <?php endforeach; ?>
                </div>
            </div>

            <!-- Theme Table -->
            <div class="card square-card mb-5">
                <div class="card-header bg-secondary text-white d-flex justify-content-between align-items-center">
                    <span><i class="fa fa-image me-2"></i> Theme / Logo</span>
                    <!-- <button class="btn btn-light btn-sm text-dark shadow-sm rounded-pill px-3" onclick="openLogoModal()">
                        <i class="fa fa-plus-circle"></i> <b>Upload / Update</b>
                    </button> -->
                </div>
                <div class="card-body table-wrapper">
                    <table id="themeTable" class="table table-bordered table-hover table-sm text-dark">
                        <thead class="table-theme-header">
                            <tr>
                                <th>#</th>
                                <th>Logo</th>
                                <!-- <th>Theme Name</th> -->
                                <!-- <th>Color</th> -->
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php
                            // If you have only one theme record, selecting WHERE id = 1 is fine.
                            $sql = "SELECT * FROM theme WHERE id = 1";
                            $query = $dbh->prepare($sql);
                            $query->execute();
                            $results = $query->fetchAll(PDO::FETCH_OBJ);
                            $cnt = 1;
                            foreach ($results as $result) { ?>
                                <tr>
                                    <td><?= htmlentities($cnt++) ?></td>
                                    <!-- show with ../ because images are stored like "assets/img/..." but admin page is inside admin/ -->
                                    <td>
                                            <!-- <img src="../<?= htmlentities($result->logo) ?>" width="60" alt="logo"> -->
                                             <img src="../<?= htmlentities($result->logo) ?>?v=<?= time() ?>" width="60" alt="logo">
                                       
                                    </td>
                                    <!-- <td><?= htmlentities($result->name) ?></td>
                                    <td>
                                        <span style="background:<?= htmlentities($result->color) ?>;padding:5px 10px;color:#fff;border-radius:3px;">
                                            <?= htmlentities($result->color) ?></span>
                                    </td> -->
                                    <td>
                                        <button class="btn btn-sm btn-info edit-logo-btn"
                                            data-id="<?= (int) $result->id ?>"
                                            data-name="<?= htmlentities($result->name, ENT_QUOTES) ?>"
                                            data-color="<?= htmlentities($result->color, ENT_QUOTES) ?>"
                                            data-logo="<?= htmlentities($result->logo, ENT_QUOTES) ?>">
                                            <i class="fa fa-edit"></i> Edit
                                        </button>
                                    </td>
                                </tr>
                            <?php } ?>
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- Logo Modal -->
            <div class="modal fade" id="logoModal" tabindex="-1" role="dialog">
                <div class="modal-dialog modal-dialog-centered modal-md">
                    <div class="modal-content">
                        <div class="modal-header bg-primary text-white">
                            <h5 class="modal-title" id="logoModalTitle">Upload / Update Logo</h5>
                            <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                        </div>
                        <form id="logoForm" enctype="multipart/form-data">
                            <!-- hidden to keep previous logo path when editing -->
                            <input type="hidden" name="oldLogo" id="oldLogo">

                            <div class="modal-body">
                                <input type="hidden" id="themeId" name="themeId">
                                <!-- <div class="form-group mb-3">
                                    <label>Theme Name</label>
                                    <input type="text" id="themeName" name="themeName" class="form-control" required>
                                </div>
                                <div class="form-group mb-3">
                                    <label>Theme Color</label>
                                    <input type="color" id="themeColor" name="themeColor" value="#000000"
                                        class="form-control form-control-color">
                                </div> -->
                                <div class="form-group mb-3">
                                    <label>Logo Image</label>
                                    <input type="file" name="logo" id="logoFile" class="form-control" accept="image/*">
                                    <div id="logoPreview" class="mt-2"></div>
                                </div>
                            </div>
                            <div class="modal-footer justify-content-center py-2">
                                <button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">
                                    <i class="fa fa-times"></i> Cancel
                                </button>
                                <button type="submit" id="saveLogoBtn" class="btn btn-success btn-sm">
                                    <i class="fa fa-save"></i> Save
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>

        </div>
    </div>

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

    <!-- Scripts -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>

    <script>
        $(document).ready(function () {
            $('#themeTable').DataTable({
                pageLength: 10,
                responsive: true,
                language: { search: "🔍 Search themes:" }
            });
        });

        function openLogoModal() {
            $("#logoModalTitle").text("Upload / Update Logo");
            $("#themeId").val("");
            $("#themeName").val("");
            $("#themeColor").val("#000000");
            $("#logoFile").val("");
            $("#logoPreview").html("");
            $("#oldLogo").val("");
            const modal = new bootstrap.Modal(document.getElementById("logoModal"));
            modal.show();
        }

        function editLogo(id, name, color, logo) {
            $("#logoModalTitle").text("Edit Logo / Theme");
            $("#themeId").val(id);
            $("#themeName").val(name);
            $("#themeColor").val(color || "#000000");
            // logo is stored as 'assets/img/...' in DB; preview needs ../ to point from admin folder
            if (logo) {
                $("#logoPreview").html('<img src="../' + logo + '" width="80" alt="logo">');
                $("#oldLogo").val(logo);
            } else {
                $("#logoPreview").html("");
                $("#oldLogo").val("");
            }
            const modal = new bootstrap.Modal(document.getElementById("logoModal"));
            modal.show();
        }

        // Live preview when a new file is selected and mark oldLogo cleared
        $("#logoFile").on("change", function () {
            const file = this.files[0];
            if (!file) {
                $("#logoPreview").html("");
                return;
            }
            const reader = new FileReader();
            reader.onload = function (e) {
                $("#logoPreview").html('<img src="' + e.target.result + '" width="80" alt="preview">');
            };
            reader.readAsDataURL(file);
            // clearing oldLogo indicates a new upload will be used
            $("#oldLogo").val("");
        });

        $("#logoForm").on("submit", function (e) {
            e.preventDefault();
            var formData = new FormData(this);

            $.ajax({
                url: "save_logo.php", // backend file (same folder)
                type: "POST",
                data: formData,
                contentType: false,
                processData: false,
                dataType: "json",
                success: function (response) {
                    $(".flash-message").remove();

                    // hide bootstrap modal using proper API
                    const modalEl = document.getElementById("logoModal");
                    const modalInstance = bootstrap.Modal.getInstance(modalEl);

                    if (response.status === "success") {
                        if (modalInstance) modalInstance.hide();
                        $(".main-content").prepend(`
                            <div class="alert alert-success flash-message text-center">
                                <strong>Success!</strong> ${response.message}
                            </div>
                        `);
                        setTimeout(() => location.reload(), 1400);
                    } else {
                        if (modalInstance) modalInstance.hide();
                        $(".main-content").prepend(`
                            <div class="alert alert-danger flash-message text-center">
                                <strong>Error!</strong> ${response.message}
                            </div>
                        `);
                    }
                },
                error: function () {
                    $(".main-content").prepend(`
                        <div class="alert alert-danger flash-message text-center">
                            ⚠️ Something went wrong! Please try again.
                        </div>
                    `);
                }
            });
        });

        // delegated listener for edit buttons
        $(document).on('click', '.edit-logo-btn', function () {
            const btn = this;
            const id = btn.dataset.id;
            const name = btn.dataset.name;
            const color = btn.dataset.color;
            const logo = btn.dataset.logo;
            editLogo(id, name, color, logo);
        });
    </script>
</body>

</html>
