<?php
session_start();
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

include("check_installation.php");

include("fetch_settings.php");

if (!isset($_SESSION["adminid"])) {
    header("Location: login.php");
    exit;
}

// Check for and handle form submissions
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $message = null;
    if (isset($_POST['update_steps'])) {
        $success = true;
        foreach ($_POST['step_id'] as $index => $step_id) {
            $step_status = isset($_POST['step_status_' . $step_id]) ? 1 : 0;
            $step_description = htmlspecialchars($_POST['step_description'][$index]);

            $stmt = $con->prepare("UPDATE steps SET step_status=?, step_description=? WHERE step_id=?");
            $stmt->bind_param('isi', $step_status, $step_description, $step_id);
            if (!$stmt->execute()) {
                $success = false;
            }
            $stmt->close();
        }
        if ($success) {
            $_SESSION['message'] = ['type' => 'success', 'text' => 'Transfer codes have been updated successfully!'];
        } else {
            $_SESSION['message'] = ['type' => 'error', 'text' => 'An error occurred while updating the transfer codes.'];
        }
    }

    if (isset($_POST['update_otp'])) {
        $otp_status = isset($_POST['otp_status']) ? 1 : 0;
        $stmt = $con->prepare("UPDATE general_settings SET otp_enabled = ? WHERE id = 1");
        $stmt->bind_param('i', $otp_status);
        if ($stmt->execute()) {
            $_SESSION['message'] = ['type' => 'success', 'text' => 'PIN settings have been updated successfully!'];
        } else {
            $_SESSION['message'] = ['type' => 'error', 'text' => 'An error occurred while updating PIN settings.'];
        }
        $stmt->close();
    }
    // Redirect to prevent form resubmission
    header("Location: transfer_codes.php");
    exit();
}

// Fetch data for display
$steps = [];
$steps_query = $con->prepare("SELECT * FROM steps");
$steps_query->execute();
$steps_result = $steps_query->get_result();
while ($row = $steps_result->fetch_assoc()) {
    // Exclude step_id = 5 as per original logic
    if ($row['step_id'] != 5) {
        $steps[] = $row;
    }
}
$steps_query->close();

$otp_enabled = 0;
$otp_query = $con->prepare("SELECT otp_enabled FROM general_settings WHERE id = 1");
$otp_query->execute();
$otp_result = $otp_query->get_result();
if ($otp_row = $otp_result->fetch_assoc()) {
    $otp_enabled = $otp_row['otp_enabled'];
}
$otp_query->close();

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Admin Dashboard - Manage Steps & PIN</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="author" content="">
    <meta name="description" content="">

    <link rel="icon" href="../<?= htmlspecialchars($system_favicon); ?>" type="image/<?= pathinfo($system_favicon, PATHINFO_EXTENSION); ?>">

    <link rel="preconnect" href="https://fonts.googleapis.com/">
    <link rel="preconnect" href="https://fonts.gstatic.com/" crossorigin>
    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;700&amp;family=Poppins:wght@400;500;700&amp;display=swap">

    <link rel="stylesheet" type="text/css" href="assets/vendor/font-awesome/css/all.min.css">
    <link rel="stylesheet" type="text/css" href="assets/vendor/bootstrap-icons/bootstrap-icons.css">
    <link rel="stylesheet" type="text/css" href="assets/vendor/overlay-scrollbar/css/overlayscrollbars.min.css">
    <link rel="stylesheet" type="text/css" href="assets/vendor/apexcharts/css/apexcharts.css">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-switch/3.3.4/css/bootstrap3/bootstrap-switch.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">

    <link rel="stylesheet" type="text/css" href="assets/css/style.css">
</head>

<body>

<main>
    <?php include "include/sidebar.php" ?>
    <div class="page-content">
        <?php include "include/topbar.php" ?>
        <div class="page-content-wrapper p-xxl-4">

            <div class="row">
                <div class="col-12 mb-4 mb-sm-5">
                    <div class="d-sm-flex justify-content-between align-items-center">
                        <h1 class="h3 mb-2 mb-sm-0">Admin Dashboard - Manage Steps & PIN</h1>
                    </div>
                </div>
            </div>

            <div class="card shadow">
                <div class="card-header border-bottom">
                    <h5 class="card-title mb-0">Manage Transfer & PIN Settings</h5>
                </div>

                <div class="card-body">
                    <?php if (isset($_SESSION['message'])): 
                        $message = $_SESSION['message'];
                        unset($_SESSION['message']); // Clear the message after displaying it
                    ?>
                        <script>
                            document.addEventListener('DOMContentLoaded', function() {
                                Swal.fire({
                                    title: '<?= $message['type'] === 'success' ? 'Success!' : 'Error!'; ?>',
                                    text: '<?= $message['text']; ?>',
                                    icon: '<?= $message['type']; ?>',
                                    confirmButtonText: 'OK'
                                });
                            });
                        </script>
                    <?php endif; ?>

                    <ul class="nav nav-tabs" id="adminTabs" role="tablist">
                        <li class="nav-item">
                            <a class="nav-link active" id="transfer-codes-tab" data-toggle="tab" href="#transfer-codes" role="tab" aria-controls="transfer-codes" aria-selected="true">Transfer Codes</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" id="otp-management-tab" data-toggle="tab" href="#otp-management" role="tab" aria-controls="otp-management" aria-selected="false">PIN Management</a>
                        </li>
                    </ul>

                    <div class="tab-content" id="adminTabsContent" style="margin-top: 30px;">
                        <div class="tab-pane fade show active" id="transfer-codes" role="tabpanel" aria-labelledby="transfer-codes-tab">
                            <form method="post" action="">
                                <?php foreach ($steps as $step): ?>
                                    <div class="form-group mb-4">
                                        <label for="step_<?= $step['step_id']; ?>">
                                            <?= htmlspecialchars($step['step_name']); ?>
                                        </label>
                                        <input type="checkbox"
                                               id="step_<?= $step['step_id']; ?>"
                                               name="step_status_<?= $step['step_id']; ?>"
                                               data-toggle="switch"
                                               <?= $step['step_status'] == 1 ? "checked" : ""; ?>>
                                        <input type="hidden" name="step_id[]" value="<?= $step['step_id']; ?>">
                                        <textarea
                                            name="step_description[]"
                                            class="form-control mt-2"
                                            placeholder="Enter step description"><?= htmlspecialchars($step['step_description']); ?></textarea>
                                    </div>
                                <?php endforeach; ?>
                                <button type="submit" name="update_steps" class="btn btn-primary mt-2">Save Transfer Codes</button>
                            </form>
                        </div>

                        <div class="tab-pane fade" id="otp-management" role="tabpanel" aria-labelledby="otp-management-tab" style="margin-top: 30px;">
                            <form method="post" action="">
                                <div class="form-group mb-4">
                                    <label for="otp_status">Enable / Disable PIN for Customers</label>
                                    <input type="checkbox" id="otp_status" name="otp_status" data-toggle="switch" <?= $otp_enabled == 1 ? "checked" : ""; ?>>
                                </div>
                                <button type="submit" name="update_otp" class="btn btn-primary mt-2">Save PIN Settings</button>
                            </form>
                        </div>
                    </div>
                </div>
            </div>

        </div>
    </div>
</main>
<script src="assets/vendor/bootstrap/dist/js/bootstrap.bundle.min.js"></script>

<script src="assets/vendor/overlay-scrollbar/js/overlayscrollbars.min.js"></script>
<script src="assets/vendor/apexcharts/js/apexcharts.min.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-switch/3.3.4/js/bootstrap-switch.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.all.min.js"></script>

<script src="assets/js/functions.js"></script>

<script>
    $(document).ready(function() {
        $("input[data-toggle='switch']").bootstrapSwitch();
    });
</script>

</body>
</html>