<?php

session_name('super_admin_session');

if (!is_dir(dirname(__DIR__) . '/session_data/super')) { mkdir(dirname(__DIR__) . '/session_data/super', 0700, true); } session_save_path(dirname(__DIR__) . '/session_data/super');

session_set_cookie_params(['path' => '/', 'httponly' => true, 'samesite' => 'Strict']);

session_start();

error_reporting(0);

include('includes/dbconnection.php');
require_once 'includes/session_term_helper.php';
$stResult = resolveCurrentSessionTerm($con);
$currentSessionName = $stResult['session_name'];
$currentTermName    = $stResult['term_name'];


require_once 'includes/wallet_helpers.php';



if (empty($_SESSION['sid'])) {

    header('location:logout.php');

    exit;

}



$msg = '';



// --- LOAD CURRENT SETTINGS ---

$settings = [];

$res = $con->query("SELECT setting_key, setting_value, label, description FROM wallet_settings ORDER BY id ASC");

if ($res) {

    while ($row = $res->fetch_assoc()) {

        $settings[$row['setting_key']] = $row;

    }

}



// --- POST HANDLER ---

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_settings'])) {

    $new_max = filter_var($_POST['max_balance'] ?? '', FILTER_VALIDATE_FLOAT);

    $new_min = filter_var($_POST['min_balance'] ?? '', FILTER_VALIDATE_FLOAT);

    $new_funding   = isset($_POST['funding_enabled'])   ? '1' : '0';

    $new_payments  = isset($_POST['payments_enabled'])  ? '1' : '0';

    $new_transfers = isset($_POST['transfers_enabled']) ? '1' : '0';



    // Validation

    $errors = [];

    if ($new_min === false || $new_min < 0) {

        $errors[] = 'Minimum Balance must be a non-negative number.';

    }

    if ($new_max === false || $new_max <= 0) {

        $errors[] = 'Maximum Balance must be a positive number.';

    }

    if (empty($errors) && $new_max < $new_min) {

        $errors[] = 'Maximum Balance must be greater than or equal to Minimum Balance.';

    }



    if (!empty($errors)) {

        $msg = 'danger|' . implode(' ', $errors);

    } else {

        $submitted = [

            'max_balance'      => (string)$new_max,

            'min_balance'      => (string)$new_min,

            'funding_enabled'  => $new_funding,

            'payments_enabled' => $new_payments,

            'transfers_enabled' => $new_transfers,

        ];



        $admin_id = (int)$_SESSION['sid'];

        mysqli_begin_transaction($con);

        try {

            foreach ($submitted as $key => $new_val) {

                $old_val = $settings[$key]['setting_value'] ?? null;

                if ($old_val === $new_val) continue; // skip unchanged



                $u = $con->prepare("UPDATE wallet_settings SET setting_value=?, updated_at=NOW(), updated_by=? WHERE setting_key=?");

                $u->bind_param("sis", $new_val, $admin_id, $key);

                $u->execute();

                $u->close();



                $l = $con->prepare("INSERT INTO wallet_settings_log (setting_key, old_value, new_value, changed_by, changed_at) VALUES (?, ?, ?, ?, NOW())");

                $l->bind_param("sssi", $key, $old_val, $new_val, $admin_id);

                $l->execute();

                $l->close();

            }

            mysqli_commit($con);

            $msg = 'success|Settings updated successfully.';



            // Reload settings after save

            $settings = [];

            $res2 = $con->query("SELECT setting_key, setting_value, label, description FROM wallet_settings ORDER BY id ASC");

            if ($res2) {

                while ($row = $res2->fetch_assoc()) {

                    $settings[$row['setting_key']] = $row;

                }

            }

        } catch (Exception $e) {

            mysqli_rollback($con);

            $msg = 'danger|Failed to save settings: ' . $e->getMessage();

        }

    }

}



// --- CHANGE HISTORY ---

$history = $con->query("SELECT * FROM wallet_settings_log ORDER BY changed_at DESC LIMIT 100");

?>

<!DOCTYPE html>

<html lang="en">

<head>

    <?php include("includes/head.php"); ?>



</head>

<body class="hold-transition sidebar-mini layout-fixed">

<div class="wrapper">

    <?php include("includes/header.php"); ?>

    <?php include("includes/sidebar.php"); ?>



    <div class="content-wrapper">

                                <section class="content-header premium-header">

    <div class="container-fluid">

        <div class="header-glass-card">

            <div class="row align-items-center">

                <div class="col-md-8">

                    <div class="title-section">

                        <div class="icon-box bg-primary-gradient shadow-sm">

                            <i class="fas fa-wallet"></i>

                        </div>

                        <div>

                            <h1 class="premium-title text-primary">

                                Wallet Management

                                <span class="premium-subtitle text-secondary">Wallet Configuration</span>

                            </h1>
                            <div class="mt-1">
                              <?php if ($currentSessionName): ?>
                                <span class="badge badge-primary mr-1">
                                  <i class="fas fa-calendar-alt"></i>
                                  <?= htmlspecialchars($currentSessionName) ?>
                                </span>
                              <?php endif; ?>
                              <?php if ($currentTermName): ?>
                                <span class="badge badge-success">
                                  <i class="fas fa-bookmark"></i>
                                  <?= htmlspecialchars($currentTermName) ?>
                                </span>
                              <?php else: ?>
                                <span class="badge badge-warning">
                                  <i class="fas fa-exclamation-triangle"></i> No active term
                                </span>
                              <?php endif; ?>
                            </div>

                        </div>

                    </div>

                </div>

                <div class="col-md-4">

                    <nav aria-label="breadcrumb">

                        <ol class="breadcrumb premium-breadcrumb">

                            <li class="breadcrumb-item"><a href="dashboard.php" class="text-primary">Home</a></li>

                            <li class="breadcrumb-item"><a href="manage_wallet.php" class="text-primary">Wallet Management</a></li>

                            <li class="breadcrumb-item active" aria-current="page">Settings</li>

                        </ol>

                    </nav>

                </div>

            </div>

        </div>

    </div>

</section> 



        <section class="content">

            <div class="container-fluid">

                <div class="row">

                    <div class="col-md-12">

                        <div class="card card-primary">

                            <div class="card-header">

                                <h5 class="card-title font-weight-bold">

                                    <i class="fas fa-cog"></i> Wallet System Settings

                                </h5>

                            </div>

                            <div class="card-body">



                                <?php if ($msg):

                                    [$type, $text] = explode('|', $msg, 2); ?>

                                    <div class="alert alert-<?php echo htmlspecialchars($type); ?> alert-dismissible rounded-xl">

                                        <button type="button" class="close" data-dismiss="alert">&times;</button>

                                        <i class="fas <?php echo $type === 'success' ? 'fa-check-circle' : 'fa-exclamation-triangle'; ?> mr-2"></i>

                                        <?php echo htmlspecialchars($text); ?>

                                    </div>

                                <?php endif; ?>



                                <!-- Settings Form -->

                                <div class="card card-outline card-primary shadow-sm rounded-2xl overflow-hidden border-0 mb-6">

                                    <div class="card-header bg-white py-3">

                                        <h3 class="card-title font-weight-bold"><i class="fas fa-sliders-h text-primary mr-2"></i> Configuration</h3>

                                    </div>

                                    <div class="card-body">

                                        <form method="POST">

                                            <div class="row">

                                                <!-- Max Balance -->

                                                <div class="col-md-6 mb-4">

                                                    <label class="text-xs font-bold text-slate-500 uppercase tracking-widest d-block mb-1">

                                                        <?php echo htmlspecialchars($settings['max_balance']['label'] ?? 'Maximum Wallet Balance (₦)'); ?>

                                                    </label>

                                                    <p class="text-xs text-muted mb-2"><?php echo htmlspecialchars($settings['max_balance']['description'] ?? ''); ?></p>

                                                    <div class="input-group">

                                                        <div class="input-group-prepend"><span class="input-group-text">₦</span></div>

                                                        <input type="number" name="max_balance" step="0.01" min="0" required

                                                               class="form-control rounded-r-lg"

                                                               value="<?php echo htmlspecialchars($settings['max_balance']['setting_value'] ?? '100000'); ?>">

                                                    </div>

                                                </div>



                                                <!-- Min Balance -->

                                                <div class="col-md-6 mb-4">

                                                    <label class="text-xs font-bold text-slate-500 uppercase tracking-widest d-block mb-1">

                                                        <?php echo htmlspecialchars($settings['min_balance']['label'] ?? 'Minimum Balance Threshold (₦)'); ?>

                                                    </label>

                                                    <p class="text-xs text-muted mb-2"><?php echo htmlspecialchars($settings['min_balance']['description'] ?? ''); ?></p>

                                                    <div class="input-group">

                                                        <div class="input-group-prepend"><span class="input-group-text">₦</span></div>

                                                        <input type="number" name="min_balance" step="0.01" min="0" required

                                                               class="form-control rounded-r-lg"

                                                               value="<?php echo htmlspecialchars($settings['min_balance']['setting_value'] ?? '0'); ?>">

                                                    </div>

                                                </div>



                                                <!-- Funding Toggle -->

                                                <div class="col-md-6 mb-4">

                                                    <label class="text-xs font-bold text-slate-500 uppercase tracking-widest d-block mb-1">

                                                        <?php echo htmlspecialchars($settings['funding_enabled']['label'] ?? 'Enable Wallet Funding'); ?>

                                                    </label>

                                                    <p class="text-xs text-muted mb-2"><?php echo htmlspecialchars($settings['funding_enabled']['description'] ?? ''); ?></p>

                                                    <div class="custom-control custom-switch">

                                                        <input type="checkbox" class="custom-control-input" id="funding_enabled" name="funding_enabled" value="1"

                                                               <?php echo ($settings['funding_enabled']['setting_value'] ?? '1') === '1' ? 'checked' : ''; ?>>

                                                        <label class="custom-control-label font-semibold" for="funding_enabled">

                                                            <?php echo ($settings['funding_enabled']['setting_value'] ?? '1') === '1' ? 'Enabled' : 'Disabled'; ?>

                                                        </label>

                                                    </div>

                                                </div>



                                                <!-- Payments Toggle -->

                                                <div class="col-md-6 mb-4">

                                                    <label class="text-xs font-bold text-slate-500 uppercase tracking-widest d-block mb-1">

                                                        <?php echo htmlspecialchars($settings['payments_enabled']['label'] ?? 'Enable Wallet Payments'); ?>

                                                    </label>

                                                    <p class="text-xs text-muted mb-2"><?php echo htmlspecialchars($settings['payments_enabled']['description'] ?? ''); ?></p>

                                                    <div class="custom-control custom-switch">

                                                        <input type="checkbox" class="custom-control-input" id="payments_enabled" name="payments_enabled" value="1"

                                                               <?php echo ($settings['payments_enabled']['setting_value'] ?? '1') === '1' ? 'checked' : ''; ?>>

                                                        <label class="custom-control-label font-semibold" for="payments_enabled">

                                                            <?php echo ($settings['payments_enabled']['setting_value'] ?? '1') === '1' ? 'Enabled' : 'Disabled'; ?>

                                                        </label>

                                                    </div>

                                                </div>



                                                <!-- Transfers Toggle -->

                                                <div class="col-md-6 mb-4">

                                                    <label class="text-xs font-bold text-slate-500 uppercase tracking-widest d-block mb-1">

                                                        <?php echo htmlspecialchars($settings['transfers_enabled']['label'] ?? 'Enable Wallet Transfers'); ?>

                                                    </label>

                                                    <p class="text-xs text-muted mb-2"><?php echo htmlspecialchars($settings['transfers_enabled']['description'] ?? 'Set to 0 to disable student-to-student wallet transfers'); ?></p>

                                                    <div class="custom-control custom-switch">

                                                        <input type="checkbox" class="custom-control-input" id="transfers_enabled" name="transfers_enabled" value="1"

                                                               <?php echo ($settings['transfers_enabled']['setting_value'] ?? '1') === '1' ? 'checked' : ''; ?>>

                                                        <label class="custom-control-label font-semibold" for="transfers_enabled">

                                                            <?php echo ($settings['transfers_enabled']['setting_value'] ?? '1') === '1' ? 'Enabled' : 'Disabled'; ?>

                                                        </label>

                                                    </div>

                                                </div>

                                            </div>



                                            <div class="d-flex align-items-center gap-3 mt-2">

                                                <button type="submit" name="save_settings" class="btn btn-primary px-5 rounded-pill shadow-sm">

                                                    <i class="fas fa-save mr-1"></i> Save Settings

                                                </button>

                                                <a href="manage_wallet.php" class="text-xs font-bold text-slate-400 hover:text-rose-500 uppercase tracking-widest ml-3">

                                                    Cancel

                                                </a>

                                            </div>

                                        </form>

                                    </div>

                                </div>



                                <!-- Change History -->

                                <div class="card card-outline card-secondary shadow-sm rounded-2xl overflow-hidden border-0">

                                    <div class="card-header bg-white py-3">

                                        <h3 class="card-title font-weight-bold"><i class="fas fa-history text-secondary mr-2"></i> Change History</h3>

                                    </div>

                                    <div class="card-body p-0">

                                        <?php if ($history && $history->num_rows > 0): ?>

                                        <div class="table-responsive">

                                            <table class="table table-hover align-middle mb-0">

                                                <thead class="bg-slate-50 text-slate-500 uppercase text-xs">

                                                    <tr>

                                                        <th class="px-4 py-3">Setting Key</th>

                                                        <th>Old Value</th>

                                                        <th>New Value</th>

                                                        <th>Changed By</th>

                                                        <th>Date / Time</th>

                                                    </tr>

                                                </thead>

                                                <tbody>

                                                    <?php while ($log = $history->fetch_assoc()): ?>

                                                    <tr>

                                                        <td class="px-4"><code class="text-xs bg-slate-100 px-2 py-1 rounded"><?php echo htmlspecialchars($log['setting_key']); ?></code></td>

                                                        <td class="text-rose-600 font-semibold text-sm"><?php echo htmlspecialchars($log['old_value'] ?? '—'); ?></td>

                                                        <td class="text-emerald-600 font-semibold text-sm"><?php echo htmlspecialchars($log['new_value'] ?? '—'); ?></td>

                                                        <td class="text-xs text-muted">Admin #<?php echo (int)$log['changed_by']; ?></td>

                                                        <td class="text-xs text-muted"><?php echo date('d M Y, h:i A', strtotime($log['changed_at'])); ?></td>

                                                    </tr>

                                                    <?php endwhile; ?>

                                                </tbody>

                                            </table>

                                        </div>

                                        <?php else: ?>

                                            <div class="text-center py-5 text-muted">

                                                <i class="fas fa-history fa-2x mb-2 opacity-30"></i>

                                                <p class="mb-0">No changes recorded yet.</p>

                                            </div>

                                        <?php endif; ?>

                                    </div>

                                </div>



                            </div><!-- /.card-body -->

                        </div><!-- /.card -->

                    </div>

                </div>

            </div>

        </section>

    </div>



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

    <?php @include("includes/foot.php"); ?>

</div>

</body>

</html>

