<?php
session_start();

include '../../includes/header.php';

$database = new Database();
$conn = $database->getConnection();

$auth = new Auth($conn);
if (!$auth->isSuperAdmin($_SESSION['user_id'])) {
    die("Access denied. Admin privileges required.");
}

require_once __DIR__ . '/../../classes/Sales.php';
$sales = new Sales($conn);

$message = '';
$messageType = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['set_allocations'])) {
    $allocations = $_POST['allocations'] ?? [];

    $successCount = 0;
    $errorCount = 0;

    foreach ($allocations as $branchId => $allocationAmount) {
        $allocationAmount = floatval(str_replace(',', '', $allocationAmount));

        try {
            $stmt = $conn->prepare("SELECT allocation_id  FROM expense_allocation WHERE allocation_branch_id = ?");
            $stmt->execute([$branchId]);
            $existing = $stmt->fetch(PDO::FETCH_ASSOC);

            if ($existing) {
                if ($allocationAmount > 0) {
                    $stmt = $conn->prepare("UPDATE expense_allocation SET allocation_amount = ?, allocation_updated_by = ? WHERE allocation_id  = ?");
                    $stmt->execute([$allocationAmount, $_SESSION['user_id'], $existing['allocation_id']]);
                } else {
                    $stmt = $conn->prepare("DELETE FROM expense_allocation WHERE allocation_id  = ?");
                    $stmt->execute([$existing['allocation_id']]);
                }
            } else if ($allocationAmount > 0) {
                $stmt = $conn->prepare("INSERT INTO expense_allocation (allocation_branch_id, allocation_amount, allocation_month , allocation_created_by ) VALUES (?, ?, ?, ?)");
                $stmt->execute([$branchId, $allocationAmount, date('Y-m'), $_SESSION['user_id']]);
            }

            $successCount++;
        } catch (Exception $e) {
            error_log("Error setting allocation for branch $branchId: " . $e->getMessage());
            $errorCount++;
        }
    }

    if ($successCount > 0) {
        $message = "Successfully updated allocations for $successCount branch(es).";
        $messageType = 'success';
        if ($errorCount > 0) {
            $message .= " $errorCount allocation(s) failed to update.";
        }
    } else {
        $message = "No allocations were updated.";
        $messageType = 'warning';
    }
}

$branches = $sales->getBranches();

$currentAllocations = [];

$stmt = $conn->prepare("SELECT allocation_branch_id , allocation_amount FROM expense_allocation");
$stmt->execute();
$allocations = $stmt->fetchAll(PDO::FETCH_ASSOC);

foreach ($allocations as $allocation) {
    $currentAllocations[$allocation['allocation_branch_id']] = $allocation['allocation_amount'];
}
?>

<div class="container mt-4">
    <div class="row mb-4">
        <div class="col-12">
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="../dashboard/admin.php">Admin Dashboard</a></li>
                    <li class="breadcrumb-item active">Expense Allocation</li>
                </ol>
            </nav>
        </div>
    </div>

    <div class="row mb-4">
        <div class="col-12">
            <h2><i class="fas fa-coins"></i> Expense Allocations </h2>
            <p class="text-muted">Set monthly expense allocation for each branch</p>
        </div>
    </div>

    <?php if ($message): ?>
        <div class="alert alert-<?php echo $messageType; ?> alert-dismissible fade show" role="alert">
            <?php echo htmlspecialchars($message); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php endif; ?>

    <div class="card">
        <div class="card-header">
            <h5>Set Expense Allocation</h5>
            <small class="text-muted">Allocations remain active until updated</small>
        </div>
        <div class="card-body">
            <form method="POST">

                <div class="table-responsive">
                    <table class="table table-striped">
                        <thead>
                            <tr>
                                <th>Branch Name</th>
                                <th>Current Allocation (MWK)</th>
                                <th>New Allocation (MWK)</th>
                                <th>Status</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($branches as $branch): ?>
                                <?php
								
								
                                $currentallocation = $currentAllocations[$branch['branch_id']] ?? 0;
								$stmt = $conn->prepare("
									SELECT SUM(amount) as used_expense 
									FROM operational_expenses 
									WHERE branch_id = ? 
									AND DATE_FORMAT(expense_date, '%Y-%m') = ?
								");
								$stmt->execute([$branch['branch_id'], date('Y-m')]);
								$expenseData = $stmt->fetch(PDO::FETCH_ASSOC);

								$currentUsed = $expenseData['used_expense'] ?? 0; 
								
								
                               /* $branchSales = $sales->getBranchSalesStats($branch['branch_id'], date('Y-m-01'), date('Y-m-t'));
								
                                $currentSales = $branchSales['stats']['total_revenue'] ?? 0;*/
                                //$balance = $currentallocation - $currentSales;
								$balance = $currentallocation - $currentUsed;
                                ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($branch['branch_name']); ?></td>
                                    <td>
                                        <strong>MWK <?php echo number_format($currentallocation, 2); ?></strong>
                                        <br>
                                       <small class="text-muted">
											Used: MWK <?php echo number_format($currentUsed, 2); ?>
										</small>
                                    </td>
                                    <td>
                                        <div class="input-group">
                                            <div class="input-group-prepend">
                                                <span class="input-group-text">MWK</span>
                                            </div>
                                            <input type="text" class="form-control text-end"
                                                   name="allocations[<?php echo $branch['branch_id']; ?>]"
                                                   value="<?php echo $currentallocation > 0 ? number_format($currentallocation, 2) : ''; ?>"
                                                   placeholder="0">
                                        </div>
                                    </td>
                                    <td>
                                        <?php if ($currentallocation > 0): ?>
                                            <?php if ($balance <= 0): ?>
                                                <span class="badge bg-danger">Allocation exhausted</span>
                                            <?php else: ?>
                                                <span class="badge bg-warning">
                                                    MWK <?php echo number_format($balance, 2); ?> remaining
                                                </span>
                                            <?php endif; ?>
                                        <?php else: ?>
                                            <span class="badge bg-secondary">No allocation set</span>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>

                <div class="mt-4">
                    <button type="submit" name="set_allocations" class="btn btn-primary">
                        <i class="fas fa-save"></i> Update Allocation
                    </button>
                    <a href="../dashboard/admin.php" class="btn btn-secondary">
                        <i class="fas fa-arrow-left"></i> Back to Dashboard
                    </a>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
document.addEventListener('input', function(e) {
    if (e.allocation.matches('input[name^="allocations"]')) {
        let value = e.allocation.value.replace(/,/g, '');
        if (!isNaN(value) && value !== '') {
            let numValue = parseFloat(value);

            if (value.indexOf('.') === -1) {
                e.allocation.value = numValue.toLocaleString('en-US', {
                    minimumFractionDigits: 2,
                    maximumFractionDigits: 2
                });
            } else {
                e.allocation.value = numValue.toLocaleString('en-US', {
                    minimumFractionDigits: 0,
                    maximumFractionDigits: 2
                });
            }
        }
    }
});

document.addEventListener('focus', function(e) {
    if (e.allocation.matches('input[name^="allocations"]') && e.allocation.value === '') {
        e.allocation.placeholder = '';
    }
});

document.addEventListener('blur', function(e) {
    if (e.allocation.matches('input[name^="allocations"]') && e.allocation.value === '') {
        e.allocation.placeholder = '0';
    }
});
</script>