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

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

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

/* HANDLE POST (UNCHANGED LOGIC) */
if($_SERVER['REQUEST_METHOD']=='POST'){

    $stmt = $pdo->prepare("
    INSERT INTO tariffs (tariff_name,utility_type)
    VALUES (?,?)
    ");

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

    // ✅ 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;">Create 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="create.php?ajax=1" id="create-form">

                <div class="form-group">
                    <label>Name</label>
                    <input 
                        name="tariff_name" 
                        class="form-control"
                        required
                    >
                </div>

                <div class="form-group">
                    <label>Utility Type</label>
                    <select name="utility_type" class="form-control">
                        <option value="WATER">Water</option>
                        <option value="ELECTRICITY">Electricity</option>
                    </select>
                </div>

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

            </form>

        </div>

    </div>

</div>

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