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

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

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

$accountId = $_GET['account_id'] ?? 0;
$unitName  = $_GET['unit_name'] ?? '';

if(!$accountId || !$unitName){
    die("Missing unit info");
}

/* ======================
REMOVE CHARGE
====================== */
if(isset($_GET['remove'])){
    $chargeId = (int)$_GET['remove'];

    $stmt = $pdo->prepare("
    DELETE FROM unit_charges
    WHERE account_id = ? AND unit_name = ? AND charge_id = ?
    ");
    $stmt->execute([$accountId,$unitName,$chargeId]);

    header("Location: manage.php?account_id=$accountId&unit_name=".urlencode($unitName));
    exit;
}

/* ======================
ADD CHARGE
====================== */
if($_SERVER['REQUEST_METHOD'] === 'POST'){

    $chargeId = $_POST['charge_id'] ?? null;

    if($chargeId){

// VALIDATE CHARGE TYPE = UNIT ONLY
$checkType = $pdo->prepare("
SELECT id FROM billing_charges 
WHERE id = ? AND applies_to = 'UNIT'
");
$checkType->execute([$chargeId]);

if(!$checkType->fetch()){
    die("Invalid charge type");
}

        $check = $pdo->prepare("
        SELECT 1 FROM unit_charges
        WHERE account_id = ? AND unit_name = ? AND charge_id = ?
        ");
        $check->execute([$accountId,$unitName,$chargeId]);

        if(!$check->fetch()){

            $stmt = $pdo->prepare("
            INSERT INTO unit_charges (account_id, unit_name, charge_id, start_date)
            VALUES (?,?,?,CURDATE())
            ");
            $stmt->execute([$accountId,$unitName,$chargeId]);

        }
    }

    header("Location: manage.php?account_id=$accountId&unit_name=".urlencode($unitName));
    exit;
}

/* ======================
LOAD ASSIGNED CHARGES
====================== */
$stmt = $pdo->prepare("
SELECT uc.charge_id, c.charge_name, c.charge_type, c.charge_value
FROM unit_charges uc

JOIN billing_charges c ON c.id = uc.charge_id
AND c.applies_to = 'UNIT'

WHERE uc.account_id = ? AND uc.unit_name = ?
");
$stmt->execute([$accountId,$unitName]);
$assigned = $stmt->fetchAll(PDO::FETCH_ASSOC);

/* ======================
LOAD AVAILABLE CHARGES
====================== */
$stmt = $pdo->prepare("
SELECT id, charge_name, charge_type, charge_value
FROM billing_charges
WHERE active = 1
AND applies_to = 'UNIT'
AND id NOT IN (
    SELECT charge_id FROM unit_charges 
    WHERE account_id = ? AND unit_name = ?
)
ORDER BY charge_name

");

$stmt->execute([$accountId,$unitName]);

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

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

<div class="container">

<h2>Manage Unit Charges</h2>
<p><strong>Unit:</strong> <?= htmlspecialchars($unitName) ?></p>

<h3>Assigned Charges</h3>

<p class="page-subtitle" style="margin-top:6px;">
These are the unit-level charges currently linked to this unit. They will be included when billing this specific unit.
</p>

<table width="100%">
<tr>
<th>Name</th>
<th>Type</th>
<th>Value</th>
<th>Action</th>
</tr>

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

<?php foreach($assigned as $c): ?>
<tr>
<td><?= htmlspecialchars($c['charge_name']) ?></td>
<td><?= $c['charge_type'] ?></td>
<td>
<?= $c['charge_type']=='percentage'
? $c['charge_value'].'%'
: 'R'.number_format($c['charge_value'],2) ?>
</td>

<td>
<a href="?account_id=<?= $accountId ?>&unit_name=<?= urlencode($unitName) ?>&remove=<?= $c['charge_id'] ?>"
style="color:red;"
onclick="return confirm('Remove charge?')">
Remove
</a>
</td>

</tr>
<?php endforeach; ?>

</table>

<br>

<h3>Add Charge</h3>

<p class="page-subtitle" style="margin-top:6px;">
Select a unit charge to attach to this unit. Only charges marked for unit billing are shown below.
</p>

<form method="POST">

<select name="charge_id" required>
<option value="">Select Charge</option>

<?php foreach($available as $c): ?>
<option value="<?= $c['id'] ?>">
<?= htmlspecialchars($c['charge_name']) ?>
(<?= $c['charge_type']=='percentage' ? $c['charge_value'].'%' : 'R'.$c['charge_value'] ?>)
</option>
<?php endforeach; ?>

</select>

<br><br>

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

</form>

</div>

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