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

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

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

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

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

    // CHECK IF PROFILES EXIST
    $stmt = $pdo->prepare("
        SELECT COUNT(*) 
        FROM tariff_profiles 
        WHERE tariff_id = ?
    ");
    $stmt->execute([$tariffId]);
    $hasProfiles = $stmt->fetchColumn();

    if($hasProfiles > 0){
        header("Location:index.php?error=tariff_has_profiles");
        exit;
    }

    // DELETE TARIFF
    $stmt = $pdo->prepare("DELETE FROM tariffs WHERE id=?");
    $stmt->execute([$tariffId]);

    header("Location:index.php?success=tariff_deleted");
    exit;
}

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

/* LOAD */
$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">

<style>

/* ===== LAYOUT ===== */
.dashboard{
    display:grid;
    grid-template-columns:260px 1fr;
    gap:16px;
    height:calc(100vh - 90px);
}

/* RIGHT STACK */
.right-panel{
    display:flex;
    flex-direction:column;
    gap:12px;
    height:100%;
}

/* ===== PANEL ===== */
.panel{
    background:#fff;
    border-radius:10px;
    border:1px solid #e5e7eb;
    display:flex;
    flex-direction:column;
    flex:1;
    overflow:hidden;
}

/* HEADER */
.panel-header{
    padding:10px 12px;
    font-weight:600;
    border-bottom:1px solid #e5e7eb;
    background:#fafafa;
    font-size:14px;
}

/* LIST */
.list{
    flex:1;
    overflow:auto;
}

/* TARIFF ITEMS */
.list-item{
    padding:10px 12px;
    border-bottom:1px solid #f1f5f9;
    cursor:pointer;
    transition:all 0.15s ease;
}

.list-item:hover{
    background:#f9fafb;
}

.list-item.active{
    background:#e0f2fe;
    border-left:3px solid #0284c7;
}

/* ===== TABLE POLISH ===== */
#profiles-container table,
#blocks-container table{
    width:100%;
    border-collapse:collapse;
    font-size:13px;
}

/* HEADERS */
#profiles-container th,
#blocks-container th{
    text-align:left !important;
    padding:9px 10px !important;
    background:#0f172a;
    color:#fff;
    font-size:12.5px;
}

/* CELLS */
#profiles-container td,
#blocks-container td{
    text-align:left !important;
    padding:7px 10px !important;
    border-bottom:1px solid #f1f5f9;
}

/* ROW HOVER */
#profiles-container tr:hover,
#blocks-container tr:hover{
    background:#f8fafc;
}

/* REMOVE HEAVY CARD STYLE */
#profiles-container .stat-card,
#blocks-container .stat-card{
    padding:6px 10px !important;
    margin:0 !important;
    box-shadow:none !important;
    border:none !important;
}

/* FORM COMPACT */
#profiles-container form,
#blocks-container form{
    margin-bottom:8px !important;
}

/* TITLES SMALLER */
#profiles-container h2,
#blocks-container h2{
    margin:6px 0 !important;
    font-size:16px !important;
}

/* ===== PAGINATION ===== */
.pagination{
    margin-top:8px;
    display:flex;
    gap:4px;
}

.pagination button{
    padding:4px 8px;
    border:none;
    border-radius:5px;
    font-size:12px;
    cursor:pointer;
    background:#f1f5f9;
}

.pagination button:hover{
    background:#e2e8f0;
}

.pagination button.active{
    background:#f2531e;
    color:#fff;
}

/* EMPTY */
.empty{
    padding:20px;
    text-align:center;
    color:#9ca3af;
    font-size:13px;
}

</style>

<div class="dashboard">

    <!-- LEFT: TARIFFS -->
    <div class="panel">
        <div class="panel-header" style="display:flex;justify-content:space-between;align-items:center;">
    <span>Tariffs</span>
    <button class="btn btn-primary" onclick="openModal('create.php')">
        + Add
    </button>
</div>

   <div class="list">
<?php foreach($tariffs as $t): ?>

    <div class="list-item tariff-item" onclick="selectTariff(<?= $t['id'] ?>, this)">

        <div>
            <strong><?= htmlspecialchars($t['tariff_name']) ?></strong><br>
            <small><?= strtoupper($t['utility_type']) ?></small>
        </div>

        <div style="margin-top:6px; display:flex; gap:5px;">

            <button 
                class="btn btn-secondary btn-sm"
                onclick="event.stopPropagation(); openModal('edit.php?id=<?= $t['id'] ?>')"
            >
                Edit
            </button>

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

        </div>

    </div>

<?php endforeach; ?>
</div>
</div>

    <!-- RIGHT -->
    <div class="right-panel">

        <!-- PROFILES -->
        <div class="panel">
            <div class="panel-header">Profiles</div>
            <div id="profiles-container" class="list empty">
                Select a tariff
            </div>
        </div>

        <!-- BLOCKS -->
        <div class="panel">
            <div class="panel-header">Blocks</div>
            <div id="blocks-container" class="list empty">
                Select a profile
            </div>
        </div>

    </div>

</div>

<script>
let activeTariffId = null;
let activeProfileId = null;

/* TOAST */
function showToast(message, type = 'success'){
    const toast = document.getElementById('edm-toast');
    toast.textContent = message;
    toast.className = 'edm-toast show ' + type;

    clearTimeout(window.edmToastTimer);
    window.edmToastTimer = setTimeout(() => {
        toast.className = 'edm-toast';
    }, 2500);
}

/* RANGE HELPERS */
function normalizeRange(from, to){
    return {
        from: parseFloat(from),
        to: (to === '' || to === null || typeof to === 'undefined') ? Infinity : parseFloat(to)
    };
}

function rangesOverlap(aFrom, aTo, bFrom, bTo){
    const a = normalizeRange(aFrom, aTo);
    const b = normalizeRange(bFrom, bTo);
    return Math.max(a.from, b.from) <= Math.min(a.to, b.to);
}

/* SELECT TARIFF */
function selectTariff(id, el){
    activeTariffId = id;
    activeProfileId = null;

    document.querySelectorAll('.tariff-item')
        .forEach(e => e.classList.remove('active'));

    el.classList.add('active');

    document.getElementById('profiles-container').innerHTML = "Loading...";
    document.getElementById('blocks-container').innerHTML = "Select a profile";

    fetch('profiles.php?tariff_id=' + id + '&ajax=1')
    .then(res => res.text())
.then(html => {

    html = html.trim(); // ðŸ”¥ correct variable

    document.getElementById('profiles-container').innerHTML = html;
       attachProfileClicks();
attachAddProfileForm();
attachDeleteProfile(); // âœ… ADD THIS LINE
paginateTable('profiles-container',10);
    })
    .catch(err => console.error(err));
}

/* LOAD BLOCKS */
function loadBlocks(profileId, keepScroll = true){
    activeProfileId = profileId;

    document.getElementById('blocks-container').innerHTML = "Loading...";

    fetch('blocks.php?profile_id=' + profileId + '&ajax=1')
    .then(res => res.text())
    .then(html => {
        document.getElementById('blocks-container').innerHTML = html;

        paginateTable('blocks-container',10);
        attachBlockInlineActions();
        attachAddBlockForm();

        if(keepScroll){
            document.getElementById('blocks-container')
                .scrollIntoView({behavior:'smooth'});
        }

        // re-highlight active profile button/row if available
        document.querySelectorAll('.load-blocks-btn').forEach(btn => {
            btn.classList.remove('active-profile');
            if(btn.getAttribute('data-id') == profileId){
                btn.classList.add('active-profile');
                const row = btn.closest('tr');
                if(row) row.classList.add('active-profile-row');
            } else {
                const row = btn.closest('tr');
                if(row) row.classList.remove('active-profile-row');
            }
        });
    })
    .catch(err => console.error(err));
}

/* PROFILE CLICK */
function attachProfileClicks(){
    document.querySelectorAll('.load-blocks-btn').forEach(btn => {
        btn.addEventListener('click', function(e){
            e.preventDefault();

            document.querySelectorAll('.load-blocks-btn').forEach(b => {
                b.classList.remove('active-profile');
                const row = b.closest('tr');
                if(row) row.classList.remove('active-profile-row');
            });

            this.classList.add('active-profile');
            const row = this.closest('tr');
            if(row) row.classList.add('active-profile-row');

            const id = this.getAttribute('data-id');
            loadBlocks(id, true);
        });
    });
}

/* PAGINATION */
function paginateTable(containerId, rowsPerPage = 10){
    const container = document.getElementById(containerId);
    const table = container.querySelector("table");
    if(!table) return;

    const tbody = table.querySelector("tbody");
    if(!tbody) return;

    const rows = Array.from(tbody.querySelectorAll("tr"));
    if(rows.length <= rowsPerPage){
        const oldPag = container.querySelector(".pagination");
        if(oldPag) oldPag.remove();
        return;
    }

    let currentPage = 1;
    const totalPages = Math.ceil(rows.length / rowsPerPage);

    function render(page){
        currentPage = page;

        rows.forEach((row, i)=>{
            row.style.display =
                (i >= (page-1)*rowsPerPage && i < page*rowsPerPage)
                ? '' : 'none';
        });

        renderControls();
    }

    function renderControls(){
        let pag = container.querySelector(".pagination");

        if(!pag){
            pag = document.createElement("div");
            pag.className = "pagination";
            container.appendChild(pag);
        }

        pag.innerHTML = '';

        for(let i=1;i<=totalPages;i++){
            const btn = document.createElement("button");
            btn.innerText = i;

            if(i === currentPage){
                btn.classList.add("active");
            }

            btn.onclick = ()=>render(i);
            pag.appendChild(btn);
        }
    }

    render(1);
}

/* OPEN MODAL */
function openModal(url){
    document.getElementById('modal').style.display = 'block';
    document.getElementById('modal-body').innerHTML = "Loading...";

    fetch(url + (url.includes('?') ? '&' : '?') + 'ajax=1')
    .then(res => res.text())
    .then(html => {
        document.getElementById('modal-body').innerHTML = html;
        attachModalForm();
    })
    .catch(err => console.error(err));
}

/* CLOSE MODAL */
function closeModal(){
    document.getElementById('modal').style.display = 'none';
}

/* MODAL FORM SUBMIT */
function attachModalForm(){
    const form = document.querySelector('#modal-body form');
    if(!form) return;

    form.addEventListener('submit', function(e){
        e.preventDefault();

        const formData = new FormData(form);

        fetch(form.action, {
            method: 'POST',
            body: formData
        })
        .then(res => res.text())
        .then(() => {
            closeModal();

            const profileId = form.querySelector('[name="profile_id"]')?.value;

            if(profileId){
                loadBlocks(profileId, false);
                showToast('Block updated successfully');
            } else {
                sessionStorage.setItem('edm_toast', 'Tariff created successfully');
                location.reload();
            }
        })
        .catch(err => console.error(err));
    });
}

/* ADD BLOCK FORM */
function attachAddBlockForm(){
    const form = document.querySelector('#blocks-container #add-block-form');
    if(!form) return;

    form.addEventListener('submit', function(e){
        e.preventDefault();

        const profileId = form.querySelector('[name="profile_id"]').value;
        const from = form.querySelector('[name="block_from"]').value.trim();
        const to = form.querySelector('[name="block_to"]').value.trim();
        const rate = form.querySelector('[name="price_per_unit"]').value.trim();
        const errorBox = document.getElementById('block-form-error');

        errorBox.style.display = 'none';
        errorBox.textContent = '';

        if(from === '' || rate === ''){
            errorBox.textContent = 'From and Rate are required.';
            errorBox.style.display = 'block';
            showToast('Please complete required fields', 'error');
            return;
        }

        let hasOverlap = false;
        document.querySelectorAll('#blocks-table tbody tr[data-block-id]').forEach(row => {
            const rowFrom = row.getAttribute('data-from');
            const rowTo   = row.getAttribute('data-to');
            if(rangesOverlap(from, to, rowFrom, rowTo)){
                hasOverlap = true;
            }
        });

        if(hasOverlap){
            errorBox.textContent = 'Block overlaps with existing tariff blocks.';
            errorBox.style.display = 'block';
            showToast('Overlap detected', 'error');
            return;
        }

        const formData = new FormData(form);

        fetch('blocks.php?profile_id=' + profileId + '&ajax=1', {
            method: 'POST',
            body: formData
        })
        .then(res => res.text())
        .then(() => {
            loadBlocks(profileId, false);
            showToast('Block added successfully');
        })
        .catch(err => console.error(err));
    });
}

/* INLINE EDIT */
function attachBlockInlineActions(){
    document.querySelectorAll('.inline-edit-btn').forEach(btn => {
        btn.addEventListener('click', function(e){
            e.preventDefault();

            const row = this.closest('tr');
            if(!row) return;

            // stop multiple edit rows at same time
            if(document.querySelector('#blocks-table tr.editing')){
                showToast('Finish current edit first', 'error');
                return;
            }

            row.classList.add('editing');

            const id = row.getAttribute('data-block-id');
            const profileId = row.getAttribute('data-profile-id');
            const from = row.getAttribute('data-from') ?? '';
            const to = row.getAttribute('data-to') ?? '';
            const rate = row.getAttribute('data-rate') ?? '';

            row.querySelector('.cell-from').innerHTML =
                `<input class="form-control" name="block_from" value="${from}">`;

            row.querySelector('.cell-to').innerHTML =
                `<input class="form-control" name="block_to" value="${to === 'null' ? '' : to}">`;

            row.querySelector('.cell-rate').innerHTML =
                `<input class="form-control" name="price_per_unit" value="${rate}">`;

            row.querySelector('.cell-actions').innerHTML = `
                <button class="btn btn-primary btn-sm save-inline-btn">Save</button>
                <button class="btn btn-secondary btn-sm cancel-inline-btn">Cancel</button>
            `;

            row.querySelector('.save-inline-btn').addEventListener('click', function(ev){
                ev.preventDefault();

                const newFrom = row.querySelector('[name="block_from"]').value.trim();
                const newTo = row.querySelector('[name="block_to"]').value.trim();
                const newRate = row.querySelector('[name="price_per_unit"]').value.trim();

                if(newFrom === '' || newRate === ''){
                    showToast('From and Rate are required', 'error');
                    return;
                }

                let hasOverlap = false;
                document.querySelectorAll('#blocks-table tbody tr[data-block-id]').forEach(other => {
                    if(other === row) return;

                    const otherFrom = other.getAttribute('data-from');
                    const otherTo = other.getAttribute('data-to');

                    if(rangesOverlap(newFrom, newTo, otherFrom, otherTo)){
                        hasOverlap = true;
                    }
                });

                if(hasOverlap){
                    showToast('Block overlaps with existing tariff blocks', 'error');
                    return;
                }

                const formData = new FormData();
                formData.append('block_from', newFrom);
                formData.append('block_to', newTo);
                formData.append('price_per_unit', newRate);
                formData.append('profile_id', profileId);

                fetch('edit_block.php?id=' + id + '&profile_id=' + profileId + '&ajax=1', {
                    method: 'POST',
                    body: formData
                })
                .then(res => res.text())
                .then(() => {
                    loadBlocks(profileId, false);
                    showToast('Block updated successfully');
                })
                .catch(err => console.error(err));
            });

            row.querySelector('.cancel-inline-btn').addEventListener('click', function(ev){
                ev.preventDefault();
                loadBlocks(profileId, false);
            });
        });
    });
}

/* REPLAY TOAST AFTER RELOAD */
document.addEventListener('DOMContentLoaded', function(){
    const msg = sessionStorage.getItem('edm_toast');
    if(msg){
        showToast(msg);
        sessionStorage.removeItem('edm_toast');
    }
});

/* =========================
   PROFILE SEARCH + FILTER
   ========================= */

document.addEventListener('input', function(e) {

    if (e.target && e.target.id === 'profile-search') {

        const container = document.getElementById('profiles-container');
        if (!container) return;

        const table = container.querySelector('#profiles-table');
        if (!table) return;

        const value = e.target.value.toLowerCase().trim();

        const filterSelect = container.querySelector('#municipality-filter');
        const filterValue = filterSelect ? filterSelect.value.toLowerCase() : '';

        table.querySelectorAll('tbody tr').forEach(row => {

            const name = row.children[0]?.textContent.toLowerCase().trim() || '';
            const municipality = row.children[1]?.textContent.toLowerCase().trim() || '';

            const matchesSearch =
                name.includes(value) || municipality.includes(value);

            const matchesFilter =
    !filterValue || municipality.includes(filterValue);

            row.style.display = (matchesSearch && matchesFilter) ? '' : 'none';

        });
    }

});

document.addEventListener('change', function(e) {

    if (e.target && e.target.id === 'municipality-filter') {

        const container = document.getElementById('profiles-container');
        if (!container) return;

        const searchInput = container.querySelector('#profile-search');
        if (!searchInput) return;

        searchInput.dispatchEvent(new Event('input'));
    }

});

document.addEventListener('click', function(e) {

    if (e.target && e.target.id === 'clear-search') {

        const container = document.getElementById('profiles-container');
        if (!container) return;

        const searchInput = container.querySelector('#profile-search');
        const filterSelect = container.querySelector('#municipality-filter');
        const table = container.querySelector('#profiles-table');

        if (searchInput) searchInput.value = '';
        if (filterSelect) filterSelect.value = '';

        if (!table) return;

        table.querySelectorAll('tbody tr').forEach(row => {
            row.style.display = '';
        });
    }

});

function attachAddProfileForm(){

    const form = document.querySelector('#profiles-container #add-profile-form');
    if(!form) return;

    form.addEventListener('submit', function(e){
        e.preventDefault();

        const formData = new FormData(form);

        fetch('profiles.php?tariff_id=' + activeTariffId + '&ajax=1', {
            method: 'POST',
            body: formData
        })
        .then(res => res.text())
        .then(() => {
            // reload profiles
            selectTariff(activeTariffId, document.querySelector('.tariff-item.active'));
            showToast('Profile added');
        });
    });
}

function attachDeleteProfile(){

    document.querySelectorAll('.delete-profile-btn').forEach(btn => {

        btn.addEventListener('click', function(){

            const id = this.getAttribute('data-id');

            if(!confirm('Delete this profile?')) return;

            fetch('profiles.php?delete=' + id + '&tariff_id=' + activeTariffId + '&ajax=1')
            .then(res => res.text())
.then(res => {

    res = res.trim(); // 🔥 VERY IMPORTANT

    if(res === 'error_blocks'){
        showToast('Cannot delete profile. Remove blocks first.', 'error');
        return;
    }

    if(res === 'delete_failed'){
        showToast('Delete failed. Try again.', 'error');
        return;
    }

    if(res === 'not_found'){
        showToast('Profile not found.', 'error');
        return;
    }

    if(res === 'success'){
        showToast('Profile deleted');
    }

    // reload profiles
    selectTariff(activeTariffId, document.querySelector('.tariff-item.active'));
});

        });

    });
}

</script>

<!-- GLOBAL MODAL -->
<div id="modal" class="modal">
    <div class="modal-content">
        <span class="close" onclick="closeModal()">&times;</span>
        <div id="modal-body">Loading...</div>
    </div>
</div>

<style>
.modal {
    display:none;
    position:fixed;
    z-index:9999;
    left:0;
    top:0;
    width:100%;
    height:100%;
    background:rgba(0,0,0,0.5);
}

.modal-content {
    background:#fff;
    margin:5% auto;
    padding:0;
    width:500px;
    border-radius:10px;
    overflow:hidden;
}

.close {
    position:absolute;
    right:12px;
    top:8px;
    font-size:20px;
    cursor:pointer;
}

.edm-toast{
    position:fixed;
    right:20px;
    bottom:20px;
    background:#16a34a;
    color:#fff;
    padding:12px 16px;
    border-radius:10px;
    font-size:13px;
    font-weight:600;
    box-shadow:0 8px 24px rgba(0,0,0,0.15);
    opacity:0;
    transform:translateY(12px);
    pointer-events:none;
    transition:all 0.25s ease;
    z-index:10001;
}

.edm-toast.error{
    background:#dc2626;
}

.edm-toast.show{
    opacity:1;
    transform:translateY(0);
}

.active-profile{
    background:#f2531e !important;
    color:#fff !important;
    border-color:#f2531e !important;
}

.active-profile-row{
    background:#fff7ed !important;
}
</style>

<div id="edm-toast" class="edm-toast"></div>
</div>

<?php if(isset($_GET['error'])): ?>
<script>
document.addEventListener('DOMContentLoaded', function(){

    <?php if($_GET['error']=='tariff_has_profiles'): ?>
        showToast('Cannot delete tariff. Remove profiles and blocks first.', 'error');
    <?php endif; ?>

});
</script>
<?php endif; ?>

<?php if(isset($_GET['success'])): ?>
<script>
document.addEventListener('DOMContentLoaded', function(){

    <?php if($_GET['success']=='tariff_deleted'): ?>
        showToast('Tariff deleted successfully');
    <?php endif; ?>

});
</script>
<?php endif; ?>

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