<?php

ini_set('display_errors',1);
error_reporting(E_ALL);

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

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

/* ======================
PAGINATION + FILTERS
====================== */
$limit = 10;

$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
if($page < 1) $page = 1;

$offset = ($page - 1) * $limit;

$search = $_GET['search'] ?? '';
$account = $_GET['account'] ?? '';
$status  = $_GET['status'] ?? '';

$where = [];
$params = [];

/* SEARCH */
if($search !== ''){
    $where[] = "(m.meter_number LIKE ? OR m.unit_name LIKE ? OR mt.tenant_name LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

/* ACCOUNT FILTER */
if($account !== ''){
    $where[] = "a.account_name = ?";
    $params[] = $account;
}

/* STATUS FILTER */
if($status !== ''){
    $where[] = "m.status = ?";
    $params[] = $status;
}

$whereSQL = $where ? 'WHERE '.implode(' AND ', $where) : '';

/* ======================
TOTAL COUNT
====================== */
$totalStmt = $pdo->prepare("
SELECT COUNT(*) 
FROM operational_meters m
LEFT JOIN billing_accounts a ON m.account_id = a.id
LEFT JOIN meter_tenants mt ON mt.meter_id = m.id AND mt.active = 1
$whereSQL
");

$totalStmt->execute($params);
$totalRows = $totalStmt->fetchColumn();
$totalPages = ceil($totalRows / $limit);

/* ======================
LOAD METERS
====================== */
$stmt = $pdo->prepare("
SELECT 
m.id,
m.meter_number,
m.unit_name,
m.status,
a.account_name,
c.customer_name,
mt.tenant_name,
mt.tenant_phone,
tp.profile_name

FROM operational_meters m

LEFT JOIN billing_accounts a ON m.account_id = a.id
LEFT JOIN billing_customers c ON a.customer_id = c.id

LEFT JOIN meter_tenants mt 
ON mt.meter_id = m.id AND mt.active = 1

LEFT JOIN tariff_profiles tp 
ON tp.id = m.tariff_profile_id

$whereSQL

ORDER BY m.id DESC
LIMIT $limit OFFSET $offset
");

$stmt->execute($params);
$meters = $stmt->fetchAll(PDO::FETCH_ASSOC);

require_once __DIR__.'/../../includes/layout.php';
?>

<div class="container">

<div class="page-header">
<h2>Operational Meters</h2>
<p class="page-subtitle">Manage all registered meters</p>
</div>

<?php if(isset($_GET['success'])): ?>
<div style="background:#d4edda;padding:10px;border-radius:6px;margin-bottom:15px;">
Meters registered successfully.
</div>
<?php endif; ?>

<?php if(isset($_GET['success']) && $_GET['success'] == 'tenant_moved_out'): ?>
<div style="background:#fff3cd;padding:10px;border-radius:6px;margin-bottom:15px;">
Tenant moved out successfully.
</div>
<?php endif; ?>

<div class="stat-card">

<!-- FILTER BAR -->
<form method="GET" style="margin-bottom:15px; display:flex; gap:10px; flex-wrap:wrap;">

<input type="text" name="search"
       value="<?= htmlspecialchars($search) ?>"
       placeholder="Search meter, unit, tenant..."
       style="flex:1;min-width:220px;padding:10px;border:1px solid #d1d5db;border-radius:10px;">

<select name="account" style="min-width:180px;padding:10px;border-radius:10px;">
<option value="">All Properties</option>

<?php
$accounts = $pdo->query("SELECT DISTINCT account_name FROM billing_accounts ORDER BY account_name")->fetchAll(PDO::FETCH_COLUMN);
foreach($accounts as $acc):
?>
<option value="<?= $acc ?>" <?= $account==$acc?'selected':'' ?>>
<?= htmlspecialchars($acc) ?>
</option>
<?php endforeach; ?>

</select>

<select name="status" style="min-width:150px;padding:10px;border-radius:10px;">
<option value="">All Status</option>
<option value="ACTIVE" <?= $status=='ACTIVE'?'selected':'' ?>>ACTIVE</option>
<option value="INACTIVE" <?= $status=='INACTIVE'?'selected':'' ?>>INACTIVE</option>
</select>

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

</form>

<table style="width:100%;border-collapse:collapse;" border="1">
<thead style="background:#f2f2f2;">
<tr>
<th>Meter</th>
<th>Unit</th>
<th>Customer</th>
<th>Property</th>
<th>Tenant</th>
<th>Status</th>
<th>Tariff</th>
<th>Action</th>
</tr>
</thead>

<tbody>

<?php if(empty($meters)): ?>
<tr>
<td colspan="8" style="text-align:center;color:#999;">
No meters found
</td>
</tr>
<?php endif; ?>

<?php foreach($meters as $m): ?>
<tr>

<td><?= htmlspecialchars($m['meter_number']) ?></td>
<td><?= htmlspecialchars($m['unit_name'] ?? '') ?></td>
<td><?= htmlspecialchars($m['customer_name'] ?? '') ?></td>
<td><?= htmlspecialchars($m['account_name'] ?? '') ?></td>

<td>
<?php if($m['tenant_name']): ?>
<?= htmlspecialchars($m['tenant_name']) ?><br>
<small><?= htmlspecialchars($m['tenant_phone']) ?></small>
<?php else: ?>
<span style="color:#999;">No Tenant</span>
<?php endif; ?>
</td>

<td><?= htmlspecialchars($m['status']) ?></td>

<td>
<?= $m['profile_name'] 
? htmlspecialchars($m['profile_name']) 
: '<span style="color:red;">No Profile</span>' ?>
</td>

<td style="position:relative;">

<button onclick="toggleMenu(<?= $m['id'] ?>)" class="btn-dark">
Actions ▾
</button>

<div id="menu_<?= $m['id'] ?>" class="action-menu">

<a href="assign_tenant.php?meter_id=<?= $m['id'] ?>">Assign Tenant</a>

<?php if(!empty($m['tenant_name'])): ?>
<a href="move_out.php?meter_id=<?= $m['id'] ?>" style="color:red;"
onclick="return confirm('Move out this tenant?')">
Move Out
</a>
<?php endif; ?>

<a href="change_profile.php?meter_id=<?= $m['id'] ?>">Change Tariff</a>

<a href="manage_charges.php?meter_id=<?= $m['id'] ?>">Manage Charges</a>

<a href="tenant_history.php?meter_id=<?= $m['id'] ?>">View History</a>

</div>

</td>

</tr>
<?php endforeach; ?>

</tbody>
</table>

<!-- PAGINATION -->
<div style="margin-top:20px; display:flex; gap:5px; flex-wrap:wrap;">

<?php if($page > 1): ?>
<a href="?page=<?= $page-1 ?>&search=<?= urlencode($search) ?>&account=<?= urlencode($account) ?>&status=<?= urlencode($status) ?>" class="btn">Prev</a>
<?php endif; ?>

<?php for($i=1; $i <= $totalPages; $i++): ?>
<a href="?page=<?= $i ?>&search=<?= urlencode($search) ?>&account=<?= urlencode($account) ?>&status=<?= urlencode($status) ?>"
class="btn <?= $i == $page ? 'btn-primary' : '' ?>">
<?= $i ?>
</a>
<?php endfor; ?>

<?php if($page < $totalPages): ?>
<a href="?page=<?= $page+1 ?>&search=<?= urlencode($search) ?>&account=<?= urlencode($account) ?>&status=<?= urlencode($status) ?>" class="btn">Next</a>
<?php endif; ?>

</div>

</div>

</div>

<script>
function toggleMenu(id){
    var menu = document.getElementById('menu_' + id);

    if(menu.style.display === 'block'){
        menu.style.display = 'none';
    }else{
        document.querySelectorAll('.action-menu').forEach(m => m.style.display='none');
        menu.style.display = 'block';
    }
}

document.addEventListener('click', function(e){
    if(!e.target.closest('.action-menu') && !e.target.closest('.btn-dark')){
        document.querySelectorAll('.action-menu').forEach(m => m.style.display='none');
    }
});
</script>

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