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

if(!$accountId){
    die("Missing account_id");
}

/* ======================
GET ACCOUNT
====================== */
$stmt = $pdo->prepare("
SELECT account_name 
FROM billing_accounts 
WHERE id = ?
");
$stmt->execute([$accountId]);
$account = $stmt->fetch(PDO::FETCH_ASSOC);

if(!$account){
    die("Account not found");
}

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

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

    header("Location: manage_charges.php?account_id=".$accountId);
    exit;
}

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

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

    if($chargeId){

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

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

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

        }
    }

    header("Location: manage_charges.php?account_id=".$accountId);
    exit;
}

/* ======================
LOAD ASSIGNED
====================== */
$stmt = $pdo->prepare("
SELECT 
    ac.charge_id,
    c.charge_name,
    c.charge_type,
    c.charge_value
FROM account_charges ac
JOIN billing_charges c ON c.id = ac.charge_id
WHERE ac.account_id = ?
");
$stmt->execute([$accountId]);
$assigned = $stmt->fetchAll(PDO::FETCH_ASSOC);

/* ======================
LOAD AVAILABLE (ONLY ACCOUNT)
====================== */
$stmt = $pdo->prepare("
SELECT id, charge_name, charge_type, charge_value
FROM billing_charges
WHERE active = 1
AND applies_to = 'ACCOUNT'
AND id NOT IN (
    SELECT charge_id FROM account_charges WHERE account_id = ?
)
ORDER BY charge_name
");
$stmt->execute([$accountId]);
$available = $stmt->fetchAll(PDO::FETCH_ASSOC);

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

<div class="container">

<div class="page-header">
<h2>Manage Account Charges</h2>
<p><strong>Account:</strong> <?= htmlspecialchars($account['account_name']) ?></p>
</div>

<div class="stat-card">

<h3>Assigned Charges</h3>

<p style="color:#6b7280;">
These charges are applied once per account during billing.
</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 account 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 ?>&remove=<?= $c['charge_id'] ?>"
style="color:red;"
onclick="return confirm('Remove this charge?')">
Remove
</a>
</td>

</tr>
<?php endforeach; ?>

</table>

<br>

<h3>Add Account Charge</h3>

<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>

</div>

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