<?php
session_start();
if (!isset($_SESSION['user_id']) || empty($_SESSION['user_id'])) {
    echo "<script>window.location.href = '/Agent/agent-login'</script>";
    exit;
}

function getTotalAmount(array $rows): float {
    $amounts = array_column($rows, 'AT_AMOUNT');
    return array_sum($amounts);
}

$conn = new mysqli($GLOBALS['host'], $GLOBALS['user'], $GLOBALS['pass'], $GLOBALS['db']);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$today = date("Y-m-d");
$userId = $_SESSION['user_id'];
$message = "";

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_collection'])) {
    $rowId = intval($_POST['row_id']);
    $collectedAmount = floatval($_POST['collected_amount']);

    $stmt = $conn->prepare("UPDATE agent_collections SET collected_amount = ? WHERE id = ? AND agent = ? AND date = ?");
    $stmt->bind_param("diss", $collectedAmount, $rowId, $userId, $today);

    if ($stmt->execute()) {
        $message = "<p class='success-msg'>✅ Collection saved successfully!</p>";
    } else {
        $message = "<p class='error-msg'>❌ Failed to save collection!</p>";
    }
    $stmt->close();
}

$targetSql = "SELECT * FROM agent_collections WHERE agent = '$userId' AND date = '$today'";
$targetResult = $conn->query($targetSql);
$targetRows = $targetResult->fetch_all(MYSQLI_ASSOC);

$sql = "SELECT * FROM {$GLOBALS['arif_tran']} WHERE AT_ADMIN = '$userId' AND DATE(AT_TIMESTAMP) = '$today'";
$result = $conn->query($sql);
$rows = $result ? $result->fetch_all(MYSQLI_ASSOC) : [];
$totalAmount = getTotalAmount($rows);

$collectable = $targetRows[0]['collectable_amount'] ?? 0;
$remaining = $collectable - $totalAmount;
$remaining = $remaining < 0 ? 0 : $remaining;

$percent = $collectable > 0 ? ($totalAmount / $collectable) * 100 : 0;

$repStmt = "SELECT * FROM agent_collections WHERE agent = '$userId' ORDER BY date DESC LIMIT 10;";
$reportsStmt = $conn->query($repStmt);
$reportRows = $reportsStmt->fetch_all(MYSQLI_ASSOC);

$conn->close();
?>

<div class="container" style="margin-bottom: 105px;">
    <h3 class="welcome-text">
        Welcome, <?= htmlspecialchars($_SESSION['name']) ?> 👋
    </h3>

    <?= $message ?>

    <div class="dashboard-total-section">
        <div class="card-box highlight">
            <h3>₹ <?= number_format($totalAmount, 2) ?></h3>
            <p>Total Collection</p>
            <div class="progress-bar">
                <div class="progress-fill" style="width: <?= $percent ?>%;"></div>
            </div>
            <small><?= round($percent, 2) ?>% Completed</small>
        </div>

        <div class="card-box normal">
            <h3>₹ <?= number_format($collectable, 2) ?></h3>
            <p>Total Collectable</p>
            <div class="remaining-text">
                Remaining: <strong>₹ <?= number_format($remaining, 2) ?></strong>
            </div>
        </div>
    </div>

    <div style="display: flex; flex-direction: row; width: 100%; justify-content: space-between; margin-top: 20px;">
        <a class="btn btn-primary w-100" href="/Agent/Receive">
            <i class="fa-solid fa-credit-card"></i>
            Receive New Payment
        </a>
        <?php if (!empty($targetRows)) : ?>
            <form method="post" class="w-100">
                <input type="hidden" name="save_collection" value="1">
                <input type="hidden" name="row_id" value="<?= $targetRows[0]['id'] ?>">
                <input type="hidden" name="collected_amount" value="<?= $totalAmount ?>">
                <button type="submit" class="btn btn-success w-100"><i class="fa-solid fa-save"></i> Save Collection</button>
            </form>
        <?php endif; ?>
    </div>

    <?php if (!empty($reportRows)) : ?>
        <div class="report-section">
            <h4 class="report-title">📊 Last 10 Days Report</h4>
            <div class="report-cards">
                <?php foreach ($reportRows as $report): ?>
                    <div class="report-card">
                        <div class="report-date">
                            <?= date("d M Y", strtotime($report['date'])) ?>
                        </div>
                        <div class="report-details">
                            <p><strong>Target:</strong> ₹ <?= number_format($report['collectable_amount'], 2) ?></p>
                            <p><strong>Collected:</strong> ₹ <?= number_format($report['collected_amount'], 2) ?></p>
                            <p><strong>Remaining:</strong> ₹ <?= number_format($report['collectable_amount'] - $report['collected_amount'], 2) ?></p>
                        </div>
                        <div class="report-progress">
                            <?php 
                                $percentDone = $report['collectable_amount'] > 0 
                                    ? ($report['collected_amount'] / $report['collectable_amount']) * 100 
                                    : 0;
                            ?>
                            <div class="progress-bar">
                                <div class="progress-fill" style="width: <?= $percentDone ?>%;"></div>
                            </div>
                            <small><?= round($percentDone, 2) ?>% Completed</small>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
    <?php endif; ?>
    <div class="android-links">
        <a href="/Agent/commission">Commission</a>
        <!-- <a href="/Agent/Report">Report</a>
        <a href="/Agent/Profile">Profile</a> -->
    </div>
</div>

<style>
    .welcome-text {
        font-size: 20px;
        font-weight: 600;
        margin-bottom: 15px;
    }
    .success-msg {
        color: green;
        background: #e6ffe6;
        padding: 8px 12px;
        border-radius: 6px;
        margin-bottom: 15px;
    }
    .error-msg {
        color: red;
        background: #ffe6e6;
        padding: 8px 12px;
        border-radius: 6px;
        margin-bottom: 15px;
    }
    .dashboard-total-section {
        display: flex;
        gap: 20px;
        margin-top: 20px;
        flex-wrap: wrap;
    }
    .card-box {
        flex: 1;
        min-width: 200px;
        background: linear-gradient(135deg, #f0f0f0ff, #d3d3d3ff);
        border-radius: 20px;
        padding: 20px;
        text-align: center;
        box-shadow: 0 6px 20px rgba(0,0,0,0.08);
    }
    .card-box.highlight {
        background: linear-gradient(135deg, #e95420, #f37249);
        color: #fff;
    }
    .progress-bar {
        width: 100%;
        height: 10px;
        background: rgba(255, 255, 255, 0.3);
        border-radius: 10px;
        margin: 10px 0;
        overflow: hidden;
    }
    .progress-fill {
        height: 100%;
        background: #fff;
        border-radius: 10px;
        transition: width 0.4s ease;
    }
    .remaining-text {
        margin-top: 8px;
        font-size: 13px;
        color: #333;
        background: #f0f0f0;
        display: inline-block;
        padding: 4px 10px;
        border-radius: 12px;
    }

    /* Report Section - Scroll Snap Slider */
    .report-section {
        margin-top: 30px;
    }
    .report-title {
        font-size: 18px;
        font-weight: 600;
        margin-bottom: 15px;
        color: #333;
    }
    .report-cards {
        display: flex;
        overflow-x: auto;
        scroll-snap-type: x mandatory;
        -webkit-overflow-scrolling: touch;
        gap: 16px;
    }
    .report-card {
        flex: 0 0 85%;
        scroll-snap-align: center;
        background: linear-gradient(135deg, #ecececff, #ffffffff);
        border-radius: 16px;
        padding: 16px;
        box-shadow: 0 4px 15px rgba(0,0,0,0.08);
    }
    .report-date {
        font-size: 14px;
        font-weight: 500;
        color: #666;
        margin-bottom: 10px;
    }
    .report-details p {
        margin: 4px 0;
        font-size: 14px;
        color: #444;
    }
    .report-progress {
        margin-top: 12px;
    }
    .report-card .progress-bar {
        width: 100%;
        height: 8px;
        background: #eee;
        border-radius: 10px;
        margin: 8px 0;
        overflow: hidden;
    }
    .report-card .progress-fill {
        height: 100%;
        background: linear-gradient(135deg, #e95420, #f37249);
        border-radius: 10px;
    }
    /* Report-cards horizontal scrollbar */
    .report-cards {
        scrollbar-width: thin; /* Firefox */
        scrollbar-color: #f37249 rgba(0,0,0,0.04); /* Firefox */
    }

    /* --- WebKit browsers (Chrome, Edge, Safari) --- */
    .report-cards::-webkit-scrollbar {
        height: 8px; /* thin horizontal scrollbar */
    }

    .report-cards::-webkit-scrollbar-track {
        background: rgba(0,0,0,0.08);
        border-radius: 10px;
    }

    .report-cards::-webkit-scrollbar-thumb {
        background: linear-gradient(90deg, #e95420, #f37249);
        border-radius: 999px;   /* ✅ fully rounded pill shape */
        min-width: 30px;
    }

    /* Hover effect */
    .report-cards::-webkit-scrollbar-thumb:hover {
        background: linear-gradient(90deg, #d7461c, #e65f3c);
    }


    .android-links {
        display: flex;
        gap: 12px;               /* বাটনের মাঝে ফাঁকা */
        flex-wrap: wrap;         /* ছোট স্ক্রিনে ভাঙবে */
        margin-top: 20px;
    }

    .android-links a {
        background: #e95420;     /* বাটনের ব্যাকগ্রাউন্ড */
        color: #fff;             /* টেক্সট কালার */
        text-decoration: none;
        padding: 10px 20px;
        border-radius: 25px;     /* গোলাকার প্রান্ত */
        font-size: 12px;
        font-weight: 500;
        box-shadow: 0 3px 8px rgba(0,0,0,0.2);
        transition: all 0.25s ease;
    }

    .android-links a:hover {
        background: #cf471c;     /* hover হলে একটু গাঢ় */
        transform: translateY(-2px);
        box-shadow: 0 6px 12px rgba(0,0,0,0.25);
    }

</style>
