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

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

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

$user_company = $_SESSION['company_id'] ?? 1;

/* ===============================
ADD CHARGE
================================ */
if(isset($_POST['add_charge'])){

$stmt=$pdo->prepare("
INSERT INTO billing_charges
(company_id, category_id, charge_name, charge_type, charge_value, applies_to, active, created_at)
VALUES (?,?,?,?,?,?,1,NOW())
");

$stmt->execute([
$user_company,
$_POST['category_id'],
$_POST['charge_name'],
$_POST['charge_type'],
$_POST['charge_value'],
$_POST['applies_to']
]);

}

/* ===============================
UPDATE CHARGE
================================ */
if(isset($_POST['update_charge'])){

$stmt=$pdo->prepare("
UPDATE billing_charges
SET charge_name=?, charge_type=?, charge_value=?
WHERE id=?
");

$stmt->execute([
$_POST['charge_name'],
$_POST['charge_type'],
$_POST['charge_value'],
$_POST['charge_id']
]);

}

/* ===============================
LOAD CHARGES
================================ */

$filterCategory = $_GET['filter_category'] ?? '';
$filterScope = $_GET['scope'] ?? '';

$sql = "
SELECT 
c.id,
c.charge_name,
c.charge_type,
c.charge_value,
c.category_id,
c.applies_to,
cat.name AS category
FROM billing_charges c
LEFT JOIN billing_charge_categories cat ON c.category_id = cat.id
WHERE (c.company_id = :company_id OR c.company_id = 0)
";

if($filterScope){
$sql .= " AND c.applies_to = :scope ";
}
if($filterCategory){
$sql .= " AND c.category_id = :category_id ";
}

$sql .= " ORDER BY c.applies_to, cat.name, c.charge_name ";

$stmt = $pdo->prepare($sql);

$params = ['company_id' => $user_company];

if($filterScope){
    $params['scope'] = $filterScope;
}

if($filterCategory){
    $params['category_id'] = $filterCategory;
}

$stmt->execute($params);

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

$cats = $pdo->query("SELECT * FROM billing_charge_categories")->fetchAll(PDO::FETCH_ASSOC);

$breadcrumb="Billing Charges";

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

<div class="container">

<div class="page-header">
<h2>Billing Charges</h2>
<p class="page-subtitle">Manage billing charges (Meter, Unit, Account).</p>
</div>

<!-- ================= ADD ================= -->
<div class="stat-card">

<h3>Add New Charge</h3>

<form method="POST" class="card-form">
<input type="hidden" name="add_charge" value="1">

<label>Charge Name</label>
<input type="text" name="charge_name" required>

<label>Category</label>
<select name="category_id" required>
<?php foreach($cats as $cat){ ?>
<option value="<?= $cat['id'] ?>">
<?= htmlspecialchars($cat['name']) ?>
</option>
<?php } ?>
</select>

<label>Applies To</label>
<select name="applies_to" required>
<option value="METER">Meter</option>
<option value="UNIT">Unit</option>
<option value="ACCOUNT">Account</option>
</select>

<label>Charge Type</label>
<select name="charge_type">
<option value="percentage">Percentage (%)</option>
<option value="fixed">Fixed Amount</option>
</select>

<label>Charge Value</label>
<input type="number" step="0.01" name="charge_value" required>

<br>
<button class="btn btn-primary">Add Charge</button>
</form>

</div>

<br>

<!-- ================= FILTER ================= -->
<div class="stat-card">

<h3>Existing Charges</h3>

<div class="tabs">
<a href="?" class="tab-btn <?= !$filterScope?'active':'' ?>">All</a>
<a href="?scope=METER" class="tab-btn <?= ($filterScope=='METER')?'active':'' ?>">Meter</a>
<a href="?scope=UNIT" class="tab-btn <?= ($filterScope=='UNIT')?'active':'' ?>">Unit</a>
<a href="?scope=ACCOUNT" class="tab-btn <?= ($filterScope=='ACCOUNT')?'active':'' ?>">Account</a>
</div>

<div class="tabs">
<?php foreach($cats as $cat){ ?>
<a href="?scope=<?= $filterScope ?>&filter_category=<?= $cat['id'] ?>"
class="tab-btn <?= ($filterCategory == $cat['id']) ? 'active' : '' ?>">
<?= htmlspecialchars($cat['name']) ?>
</a>
<?php } ?>
<a href="?scope=<?= $filterScope ?>" class="tab-btn <?= !$filterCategory?'active':'' ?>">All</a>
</div>

<div class="table-wrap">

<table>
<thead>
<tr>
<th>Applies To</th>
<th>Category</th>
<th>Name</th>
<th>Type</th>
<th>Value</th>
<th>Status</th>
<th>Actions</th>
</tr>
</thead>

<tbody>

<?php if(!$charges): ?>
<tr><td colspan="7">No charges found</td></tr>
<?php else: ?>

<?php foreach($charges as $c): ?>

<tr>

<td>
<?php
$label = '';
$color = '#eee';

if($c['applies_to']=='METER'){ $label='Meter'; $color='#fef3c7'; }
elseif($c['applies_to']=='UNIT'){ $label='Unit'; $color='#dbeafe'; }
else { $label='Account'; $color='#e9d5ff'; }
?>

<span style="background:<?= $color ?>;padding:4px 8px;border-radius:6px;font-size:12px;">
<?= $label ?>
</span>
</td>

<td><?= htmlspecialchars($c['category'] ?? 'General') ?></td>

<td>
<form method="POST" style="display:flex;gap:10px;">
<input type="hidden" name="update_charge" value="1">
<input type="hidden" name="charge_id" value="<?= $c['id'] ?>">

<input type="text" name="charge_name" value="<?= htmlspecialchars($c['charge_name']) ?>">
</td>

<td>
<select name="charge_type">
<option value="percentage" <?= $c['charge_type']=='percentage'?'selected':'' ?>>%</option>
<option value="fixed" <?= $c['charge_type']=='fixed'?'selected':'' ?>>Fixed</option>
</select>
</td>

<td>
<input type="number" step="0.01" name="charge_value" value="<?= $c['charge_value'] ?>">
</td>

<td>
<span style="color:green">Active</span>
</td>

<td>
<button class="btn btn-primary">Save</button>
</form>
</td>

</tr>

<?php endforeach; ?>

<?php endif; ?>

</tbody>
</table>

</div>

</div>

</div>

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