<?php
require_once __DIR__.'/../../../includes/auth.php';
requireLogin();

require_once __DIR__.'/../../../config/database.php';

/* AJAX DETECT */
$isAjax = isset($_GET['ajax']);

$id = (int)$_GET['id'];

/* LOAD TARIFF */

$stmt = $pdo->prepare("
SELECT *
FROM tariffs
WHERE id=?
");

$stmt->execute([$id]);

$tariff = $stmt->fetch(PDO::FETCH_ASSOC);

if(!$tariff){
    echo "Tariff not found";
    exit;
}

/* UPDATE (UNCHANGED LOGIC) */

if($_SERVER['REQUEST_METHOD']=='POST'){

    $stmt = $pdo->prepare("
    UPDATE tariffs
    SET tariff_name=?, utility_type=?
    WHERE id=?
    ");

    $stmt->execute([
        $_POST['tariff_name'],
        $_POST['utility_type'],
        $id
    ]);

    // ✅ ONLY CHANGE: prevent redirect if AJAX
    if($isAjax){
        echo "success";
        exit;
    }

    header("Location:index.php");
    exit;
}

/* LOAD LAYOUT ONLY IF NOT AJAX */
if(!$isAjax){
    require_once __DIR__.'/../../../includes/header.php';
    require_once __DIR__.'/../../../includes/sidebar.php';
}
?>

<div class="<?= $isAjax ? '' : 'main-content' ?>">

    <div class="<?= $isAjax ? 'panel' : 'page-wrapper' ?>">

        <!-- HEADER -->
        <div class="<?= $isAjax ? 'panel-header' : 'page-header' ?>">
            <h2 style="margin:0; font-size:16px;">Edit Tariff</h2>

            <?php if(!$isAjax): ?>
                <a href="index.php" class="btn btn-secondary">
                    Back to Tariffs
                </a>
            <?php endif; ?>
        </div>

        <!-- BODY -->
        <div style="padding:15px;">

            <form method="POST" action="" id="edit-form">

                <div class="form-group">
                    <label>Name</label>
                    <input
                        name="tariff_name"
                        class="form-control"
                        value="<?= htmlspecialchars($tariff['tariff_name']) ?>"
                        required
                    >
                </div>

                <div class="form-group">
                    <label>Utility Type</label>
                    <select name="utility_type" class="form-control">

                        <option value="WATER" <?= $tariff['utility_type']=='WATER'?'selected':'' ?>>
                            Water
                        </option>

                        <option value="ELECTRICITY" <?= $tariff['utility_type']=='ELECTRICITY'?'selected':'' ?>>
                            Electricity
                        </option>

                    </select>
                </div>

                <div style="margin-top:15px;">
                    <button class="btn btn-primary">
                        Update Tariff
                    </button>
                </div>

            </form>

        </div>

    </div>

</div>

<?php
if(!$isAjax){
    require_once __DIR__.'/../../../includes/footer.php';
}
?>