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

// Get agent list
$getAgentListsQuery = "SELECT * FROM " . $GLOBALS['arif_users'];
$agentResult = $conn->query($getAgentListsQuery);
$agentList = [];
if ($agentResult && $agentResult->num_rows > 0) {
    while ($row = $agentResult->fetch_assoc()) {
        $agentList[] = $row;
    }
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $collectableAmount = isset($_POST['COLLECTABLE_AMOUNT']) ? floatval($_POST['COLLECTABLE_AMOUNT']) : 0;
    $collectableAgent = isset($_POST['COLLECTABLE_AGENT']) ? $_POST['COLLECTABLE_AGENT'] : null;

    if ($collectableAmount > 0 && $collectableAgent) {
        $stmt = $conn->prepare("INSERT INTO agent_collections (agent, collectable_amount, collected_amount, date) VALUES (?, ?, 0, CURDATE())");
        $stmt->bind_param("sd", $collectableAgent, $collectableAmount);

        if ($stmt->execute()) {
            echo "<div class='alert alert-success'>Target assigned successfully!</div>";
        } else {
            echo "<div class='alert alert-danger'>Error: " . $stmt->error . "</div>";
        }
        $stmt->close();
    } else {
        echo "<div class='alert alert-warning'>Please enter a valid amount and select an agent.</div>";
    }
}

$conn->close();
?>

<div class="container">
    <h2>Agent Collection Targets</h2>
    <form method="post" style="display: flex; flex-direction: column; gap: 15px;">
        <div>
            <label for="COLLECTABLE_AMOUNT">Collectable Amount:</label>
            <input id="COLLECTABLE_AMOUNT" class="form-control" name="COLLECTABLE_AMOUNT" type="text" placeholder="Enter Amount" />
        </div>
        <div>
            <label for="COLLECTABLE_AGENT">Collectable Agent:</label>
            <select class="form-control" name="COLLECTABLE_AGENT" id="COLLECTABLE_AGENT">
                <?php 
                    foreach($agentList as $agent){
                        echo '<option value="'.$agent['user_id'].'">'.$agent['user_id'].' / '.$agent['user_name'].'</option>';
                    }
                ?>
            </select>
        </div>
        <button class="btn btn-primary" type="submit">Assign Target</button>
    </form>
</div>
