<?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';

$profileId = isset($_GET['profile_id']) ? (int)$_GET['profile_id'] : 0;

/* DELETE BLOCK */

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

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

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

header("Location: blocks.php?profile_id=".$profileId);
exit;

}

/* ADD BLOCK WITH VALIDATION */

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

$from = (float)$_POST['block_from'];
$to   = $_POST['block_to'] !== '' ? (float)$_POST['block_to'] : null;
$rate = (float)$_POST['price_per_unit'];

/* CHECK OVERLAP WITH ANY EXISTING BLOCK */

$stmt = $pdo->prepare("
SELECT COUNT(*)
FROM tariff_blocks
WHERE tariff_profile_id = ?
AND (
    (block_from <= ? AND (block_to >= ? OR block_to IS NULL))
    OR
    (? <= block_from AND (? >= block_to OR block_to IS NULL))
)
");

$stmt->execute([
$profileId,
$from,
$from,
$to,
$to
]);

$exists = $stmt->fetchColumn();

if($exists){

$error = "Block overlaps with existing tariff blocks.";

}

/* INSERT IF VALID */

if(!isset($error)){

$stmt = $pdo->prepare("
INSERT INTO tariff_blocks (tariff_profile_id,block_from,block_to,price_per_unit)
VALUES (?,?,?,?)
");

$stmt->execute([
$profileId,
$from,
$to,
$rate
]);

}

}

/* LOAD BLOCKS */

$blocks = $pdo->prepare("
SELECT *
FROM tariff_blocks
WHERE tariff_profile_id=?
ORDER BY block_from
");

$blocks->execute([$profileId]);

$rows = $blocks->fetchAll(PDO::FETCH_ASSOC);

/* ===============================
GET PROFILE + TARIFF
=============================== */


$stmt = $pdo->prepare("
    SELECT tariff_id
    FROM tariff_profiles
    WHERE id = ?
    LIMIT 1
");
$stmt->execute([$profileId]);
$tariffId = $stmt->fetchColumn();

if (!$tariffId) {
    $tariffId = 0; // prevent breaking AJAX
}

/* ===============================
LOAD LAYOUT
=============================== */

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

<?php if(!$isAjax): ?>
<div class="main-content">
<?php endif; ?>

<style>
.table button,
.table .btn {
    font-family: 'Poppins', sans-serif;
    font-size: 12.5px;
    font-weight: 500;
}

.table .btn {
    padding: 4px 10px;
}
</style>

<div class="page-header">
<h2>Tariff Blocks</h2>
<p style="font-size:13px; color:#6b7280; margin-bottom:10px;">
Define usage ranges and pricing. Each block represents a consumption range with its own rate.
</p>
</div>


<div class="stat-card">

<h3>Add Block</h3>

<div id="block-form-error" class="alert alert-danger" style="display:none;"></div>

<?php if(isset($error)): ?>
<div class="alert alert-danger">
<?= $error ?>
</div>
<?php endif; ?>

<form method="POST" class="form-row" id="add-block-form" novalidate>
<input type="hidden" name="profile_id" value="<?= $profileId ?>">

<div class="form-group">
<label>From</label>
<input name="block_from" required>
</div>

<div class="form-group">
<label>To</label>
<input name="block_to">
</div>

<div class="form-group">
<label>Rate</label>
<input name="price_per_unit" required>
</div>

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

</form>

</div>


<div class="stat-card">

<h3>Blocks</h3>

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

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

<thead>
<tr>
<th>From</th>
<th>To</th>
<th>Rate</th>
<th>Actions</th>
</tr>
</thead>

<tbody>

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

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

<?php endif; ?>

<?php foreach($rows as $r): ?>

<tr
    data-block-id="<?= $r['id'] ?>"
    data-profile-id="<?= $profileId ?>"
    data-from="<?= htmlspecialchars($r['block_from']) ?>"
    data-to="<?= htmlspecialchars($r['block_to']) ?>"
    data-rate="<?= htmlspecialchars($r['price_per_unit']) ?>"
>
    <td class="cell-from"><?= $r['block_from'] ?></td>
    <td class="cell-to"><?= $r['block_to'] ?></td>
    <td class="cell-rate"><?= $r['price_per_unit'] ?></td>

    <td class="cell-actions">

        <button
            class="btn btn-primary btn-sm inline-edit-btn"
            type="button"
        >
            Inline Edit
        </button>

        <button 
            class="btn btn-secondary btn-sm"
            type="button"
            onclick="event.preventDefault(); openModal('edit_block.php?id=<?= $r['id'] ?>&profile_id=<?= $profileId ?>')"
        >
            Modal Edit
        </button>

        <a href="blocks.php?delete=<?= $r['id'] ?>&profile_id=<?= $profileId ?>" 
        class="btn btn-danger btn-sm"
        onclick="return confirm('Delete this block?')">
        Delete
        </a>

    </td>

</tr>

<?php endforeach; ?>

</tbody>

</table>

</div>

</div>

<?php if(!$isAjax): ?>
</div>
<?php endif; ?>

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