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

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

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


/* DELETE TARIFF */

if(isset($_GET['delete'])){

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

$stmt->execute([$_GET['delete']]);

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

}


/* SEARCH */

$search = '';

if(isset($_GET['search'])){
$search = trim($_GET['search']);
}


/* LOAD TARIFFS */

$stmt = $pdo->prepare("
SELECT id, tariff_name, utility_type
FROM tariffs
WHERE tariff_name LIKE ?
ORDER BY tariff_name
");

$stmt->execute(['%'.$search.'%']);

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


require_once __DIR__.'/../../../includes/header.php';
require_once __DIR__.'/../../../includes/sidebar.php';
?>

<div class="main-content">

<div class="page-header">

<h2>Tariffs</h2>

<a href="create.php" class="btn btn-primary">
Add Tariff
</a>

</div>


<div class="stat-card">

<form method="GET" style="display:flex;gap:10px;max-width:400px;margin-bottom:15px;">

<input 
type="text"
name="search"
placeholder="Search tariffs..."
value="<?= htmlspecialchars($search) ?>"
class="form-control"
>

<button class="btn btn-primary">
Search
</button>

<a href="index.php" class="btn btn-secondary">
Reset
</a>

</form>

</div>


<div class="stat-card">

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

<table class="table">

<thead>

<tr>
<th style="width:80px;">ID</th>
<th>Tariff Name</th>
<th style="width:150px;">Utility</th>
<th style="width:260px;">Actions</th>
</tr>

</thead>

<tbody>

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

<tr>
<td colspan="4" style="text-align:center;padding:30px;">
No tariffs found
</td>
</tr>

<?php endif; ?>

<?php foreach($tariffs as $t): ?>

<tr>

<td><?= $t['id'] ?></td>

<td>
<strong><?= htmlspecialchars($t['tariff_name']) ?></strong>
</td>

<td>
<?= strtoupper(htmlspecialchars($t['utility_type'])) ?>
</td>

<td>

<a href="#" onclick="loadProfiles(<?= $t['id'] ?>); return false;" class="btn btn-secondary btn-sm">
Profiles
</a>

<a href="edit.php?id=<?= $t['id'] ?>" class="btn btn-primary btn-sm">
Edit
</a>

<a href="index.php?delete=<?= $t['id'] ?>" 
class="btn btn-danger btn-sm"
onclick="return confirm('Delete this tariff?')">
Delete
</a>

</td>

</tr>

<?php endforeach; ?>

</tbody>

</table>

</div>

</div>
<div class="stat-card" id="profiles-container" style="margin-top:20px;"></div>
<div class="stat-card" id="blocks-container" style="margin-top:20px;"></div>

<script>
function loadProfiles(tariffId){
    fetch('profiles.php?tariff_id=' + tariffId + '&ajax=1')
    .then(res => res.text())
    .then(html => {
        document.getElementById('profiles-container').innerHTML = html;

        // clear blocks
        document.getElementById('blocks-container').innerHTML = '';

        // attach click events AFTER HTML loads
        attachBlockClicks();
    })
    .catch(err => console.error(err));
}

function loadBlocks(profileId){
    fetch('blocks.php?profile_id=' + profileId + '&ajax=1')
    .then(res => res.text())
    .then(html => {
        document.getElementById('blocks-container').innerHTML = html;
    })
    .catch(err => console.error(err));
}

// 🔥 THIS IS THE FIX
function attachBlockClicks(){
    document.querySelectorAll('.load-blocks-btn').forEach(btn => {
        btn.addEventListener('click', function(e){
            e.preventDefault();
            const id = this.getAttribute('data-id');
            loadBlocks(id);
        });
    });
}
</script>

<?php require_once __DIR__.'/../../../includes/footer.php'; ?>