<?php
ini_set('display_errors',1);
error_reporting(E_ALL);

require_once __DIR__.'/../../../includes/auth.php';
requireLogin();
$isAjax = isset($_GET['ajax']);
require_once __DIR__.'/../../../config/database.php';

$tariffId = isset($_GET['tariff_id']) ? (int)$_GET['tariff_id'] : 0;

/* DELETE PROFILE */
if(isset($_GET['delete'])){

    $profileId = (int)$_GET['delete'];

    // 🔒 VERIFY PROFILE EXISTS + GET REAL TARIFF
    $stmt = $pdo->prepare("
        SELECT id 
        FROM tariff_profiles 
        WHERE id = ?
    ");
    $stmt->execute([$profileId]);

    if(!$stmt->fetch()){
        echo "not_found";
        exit;
    }

    // 🔒 CHECK BLOCKS (STRICT RELATION)
    $stmt = $pdo->prepare("
        SELECT COUNT(*) 
        FROM tariff_blocks 
        WHERE profile_id = ?
    ");
    $stmt->execute([$profileId]);

    if($stmt->fetchColumn() > 0){
        echo "error_blocks";
        exit;
    }

    // ✅ REAL DELETE (NO DEPENDENCY ON tariff_id)
    $stmt = $pdo->prepare("
        DELETE FROM tariff_profiles 
        WHERE id = ?
    ");
    $stmt->execute([$profileId]);

    // 🔥 VERIFY DELETE ACTUALLY HAPPENED
    if($stmt->rowCount() === 0){
        echo "delete_failed";
        exit;
    }

    echo "success";
    exit;
}
/* ADD PROFILE */

if(isset($_POST['profile_name'])){

    $stmt = $pdo->prepare("
        INSERT INTO tariff_profiles (tariff_id,profile_name,municipality)
        VALUES (?,?,?)
    ");

    $stmt->execute([
        $tariffId,
        $_POST['profile_name'],
        $_POST['municipality']
    ]);

    // ðŸ”¥ STOP PAGE REDIRECT
    if($isAjax){
        echo "ok";
        exit;
    }
}

/* LOAD PROFILES */

$stmt = $pdo->prepare("
SELECT *
FROM tariff_profiles
WHERE tariff_id=?
ORDER BY profile_name
");

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

$profiles = $stmt->fetchAll(PDO::FETCH_ASSOC);

if(!$isAjax){
    require_once __DIR__.'/../../../includes/header.php';
    require_once __DIR__.'/../../../includes/sidebar.php';
}
?>
<div class="main-content">

<style>
.page-header,
.stat-card {
    text-align: left !important;
}
</style>

<div class="page-header">
<h2>Tariff Profiles</h2>
<p style="font-size:13px; color:#6b7280; margin-bottom:10px;">
Create tariff profiles for different municipalities. Each profile will have its own pricing structure.
</p>
</div>


<div class="stat-card">

<h3>Add Municipality Profile</h3>


<form method="POST" class="form-row" id="add-profile-form">

<div class="form-group">
<label>Profile Name</label>
<input name="profile_name" required>
</div>

<div class="form-group">
<label>Municipality</label>
<input name="municipality">
</div>

<div class="form-group" style="align-self:flex-end;">
<button class="btn btn-primary">
Add Profile
</button>
</div>

</form>

</div>


<div class="stat-card">

<h3>Profiles</h3>

<div style="display:flex; gap:8px; margin-bottom:10px; align-items:center; flex-wrap:wrap;">

    <!-- SEARCH -->
    <input 
        type="text" 
        id="profile-search" 
        placeholder="Search profile or municipality..." 
        class="form-control"
        style="max-width:250px;"
    >

    <!-- FILTER -->
    <select id="municipality-filter" class="form-control" style="max-width:200px;">
        <option value="">All Municipalities</option>

        <?php
        $uniqueMunicipalities = array_unique(array_column($profiles, 'municipality'));
        sort($uniqueMunicipalities);

        foreach($uniqueMunicipalities as $m):
        ?>
            <option value="<?= htmlspecialchars(trim(strtolower($m))) ?>">
                <?= htmlspecialchars($m) ?>
            </option>
        <?php endforeach; ?>
    </select>

    <!-- CLEAR -->
    <button 
        type="button" 
        class="btn btn-secondary btn-sm" 
        id="clear-search"
    >
        Clear
    </button>

</div>

<div style="overflow-x:auto;">

<table class="table" id="profiles-table">

<thead>
<tr>
<th>Profile</th>
<th>Municipality</th>
<th>Actions</th>
</tr>
</thead>

<tbody>

<?php if(empty($profiles)): ?>

<tr>
<td colspan="3" style="text-align:center;padding:20px;">
No profiles created yet
</td>
</tr>

<?php endif; ?>

<?php foreach($profiles as $p): ?>

<tr>

<td><?= htmlspecialchars($p['profile_name']) ?></td>

<td><?= htmlspecialchars($p['municipality']) ?></td>

<td>

<a href="#" class="btn btn-primary btn-sm load-blocks-btn" data-id="<?= $p['id'] ?>">
    Blocks
</a>

<button 
    class="btn btn-danger btn-sm delete-profile-btn" 
    data-id="<?= $p['id'] ?>"
>
    Delete
</button>

</td>

</tr>

<?php endforeach; ?>

</tbody>

</table>

</div>

</div>



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