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


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


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


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


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

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

    $successCount = 0;
    $errorCount = 0;

    foreach ($targets as $branchId => $targetAmount) {
        $targetAmount = floatval(str_replace(',', '', $targetAmount));


        try {

            $stmt = $conn->prepare("SELECT target_id FROM sales_targets WHERE branch_id = ?");
            $stmt->execute([$branchId]);
            $existing = $stmt->fetch(PDO::FETCH_ASSOC);

            if ($existing) {
                if ($targetAmount > 0) {

                    $stmt = $conn->prepare("UPDATE sales_targets SET target_amount = ?, updated_by = ? WHERE target_id = ?");
                    $stmt->execute([$targetAmount, $_SESSION['user_id'], $existing['target_id']]);
                } else {

                    $stmt = $conn->prepare("DELETE FROM sales_targets WHERE target_id = ?");
                    $stmt->execute([$existing['target_id']]);
                }
            } else if ($targetAmount > 0) {

                $stmt = $conn->prepare("INSERT INTO sales_targets (branch_id, target_amount, target_month, created_by) VALUES (?, ?, ?, ?)");
                $stmt->execute([$branchId, $targetAmount, date('Y-m'), $_SESSION['user_id']]);
            }
            $successCount++;
        } catch (Exception $e) {
            error_log("Error setting target for branch $branchId: " . $e->getMessage());
            $errorCount++;
        }
    }

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


$branches = $sales->getBranches();


$currentTargets = [];

$stmt = $conn->prepare("SELECT branch_id, target_amount FROM sales_targets");
$stmt->execute();
$targets = $stmt->fetchAll(PDO::FETCH_ASSOC);

foreach ($targets as $target) {
    $currentTargets[$target['branch_id']] = $target['target_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">Sales Targets</li>
                </ol>
            </nav>
        </div>
    </div>

    <div class="row mb-4">
        <div class="col-12">
            <h2><i class="fas fa-bullseye"></i> Sales Targets Management</h2>
            <p class="text-muted">Set monthly sales targets 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 Sales Targets</h5>
            <small class="text-muted">Targets 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 Target (MWK)</th>
                                <th>New Target (MWK)</th>
                                <th>Status</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($branches as $branch): ?>
                                <?php
                                $currentTarget = $currentTargets[$branch['branch_id']] ?? 0;
                                $branchSales = $sales->getBranchSalesStats($branch['branch_id'], date('Y-m-01'), date('Y-m-t'));
                                $currentSales = $branchSales['stats']['total_revenue'] ?? 0;
                                $balance = $currentTarget - $currentSales;
                                ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($branch['branch_name']); ?></td>
                                    <td>
                                        <strong>MWK <?php echo number_format($currentTarget, 2); ?></strong>
                                        <br>
                                        <small class="text-muted">Current: MWK <?php echo number_format($currentSales, 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="targets[<?php echo $branch['branch_id']; ?>]"
                                                   value="<?php echo $currentTarget > 0 ? number_format($currentTarget, 2) : ''; ?>"
                                                   placeholder="0">
                                        </div>
                                    </td>
                                    <td>
                                        <?php if ($currentTarget > 0): ?>
                                            <?php if ($balance <= 0): ?>
                                                <span class="badge bg-success">Target Met</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 target set</span>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>

                <div class="mt-4">
                    <button type="submit" name="set_targets" class="btn btn-primary">
                        <i class="fas fa-save"></i> Update Targets
                    </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.target.matches('input[name^="targets"]')) {
        let value = e.target.value.replace(/,/g, '');
        if (!isNaN(value) && value !== '') {

            let numValue = parseFloat(value);
            if (value.indexOf('.') === -1) {

                e.target.value = numValue.toLocaleString('en-US', {
                    minimumFractionDigits: 2,
                    maximumFractionDigits: 2
                });
            } else {

                e.target.value = numValue.toLocaleString('en-US', {
                    minimumFractionDigits: 0,
                    maximumFractionDigits: 2
                });
            }
        }
    }
});


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


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

