<?php
// This script assumes it is included in admin_dashboard.php, 
// so the $conn object (database connection) is available.

$status_message = '';
$users = []; // Array to store user names for the dropdown

// --- A. Fetch List of users for Dropdown ---
try {
    // Select user_id and username from the existing users table
    $sql_users = "SELECT user_id, username FROM users ORDER BY username ASC";
    $result_users = $conn->query($sql_users);
    if ($result_users) {
        while ($row = $result_users->fetch_assoc()) {
            $users[] = $row;
        }
    }
} catch (Exception $e) {
    // Database connection error handling
    $status_message = "<div class='alert alert-error'>Error fetching users list: " . htmlspecialchars($e->getMessage()) . "</div>";
}


// --- B. Logic for Adding a New Asset Record ---
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['add_asset'])) {
    
    // Get and sanitize input
    $user_id = (int)$_POST['user_id'];
    $asset_details = trim($_POST['asset_details']);
    $collection_date = trim($_POST['collection_date']);
    $return_date = empty(trim($_POST['return_date'])) ? null : trim($_POST['return_date']);

    if (empty($user_id) || empty($asset_details) || empty($collection_date)) {
        $status_message = "<div class='alert alert-error'>user, Asset Details, and Collection Date are required.</div>";
    } else {
        // Determine the SQL query based on whether a return date was provided
        $sql = "INSERT INTO assets (user_id, asset_details, collection_date, return_date) 
                VALUES (?, ?, ?, ?)";
        
        $stmt = $conn->prepare($sql);
        
        if ($stmt === false) {
             $status_message = "<div class='alert alert-error'>Database prepare error: " . $conn->error . "</div>";
        } else {
            // If return_date is null, bind_param still requires a type, so we use 's' (string) but pass null
            $stmt->bind_param("isss", $user_id, $asset_details, $collection_date, $return_date);
        
            if ($stmt->execute()) {
                $status_message = "<div class='alert alert-info'>Success! Asset record for user ID {$user_id} created successfully.</div>";
            } else {
                error_log("Asset insert failed: " . $stmt->error);
                $status_message = "<div class='alert alert-error'>Error adding asset record: " . $stmt->error . "</div>";
            }
            $stmt->close();
        }
    }
}


// --- C. Logic for Viewing All Assets (Data Fetch) ---
$asset_data = [];
$sql_view = "SELECT 
                a.asset_id, 
                e.username AS user_name, 
                a.asset_details, 
                a.collection_date, 
                a.return_date,
                a.created_at
            FROM assets a
            JOIN users e ON a.user_id = e.user_id
            ORDER BY a.collection_date DESC";

$result_assets = $conn->query($sql_view);

if ($result_assets) {
    while ($row = $result_assets->fetch_assoc()) {
        $asset_data[] = $row;
    }
}
?>

<style>
    /* Specific styling for the Asset Modal/Popup */
    .asset-modal {
        display: none; /* Hidden by default */
        position: fixed; 
        z-index: 1001; 
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        overflow: auto;
        background-color: rgba(0,0,0,0.6); 
        backdrop-filter: blur(5px);
    }
    .asset-modal-content {
        background-color: #fff;
        margin: 5% auto; 
        padding: 25px;
        border-radius: 12px;
        width: 95%; 
        max-width: 1200px; /* Wider for asset details */
        box-shadow: 0 10px 30px rgba(0,0,0,0.5);
        position: relative;
        max-height: 85vh;
        overflow-y: auto;
    }
    .modal-close {
        color: #aaa;
        float: right;
        font-size: 36px;
        font-weight: bold;
        transition: color 0.3s;
    }
    .modal-close:hover,
    .modal-close:focus {
        color: #e74c3c;
        text-decoration: none;
        cursor: pointer;
    }
    .data-table th, .data-table td {
        padding: 10px;
        border: 1px solid #ddd;
        text-align: left;
    }
    .data-table thead tr {
        background-color: #2c3e50; 
        color: white;
    }
    .asset-pending {
        background-color: #f7e0e0; /* Light red background for pending returns */
        font-weight: bold;
    }
</style>

<!-- --- Asset Assignment Form --- -->
<div class="form-card">
    <h3>Asset Assignment and Collection</h3>
    <p>Use this form to record assets given to or returned by users.</p>
    
    <?php echo $status_message; ?>

    <form action="admin_dashboard.php?page=manage_assets" method="post">
        
        <label for="user_id">User Name:</label>
        <select name="user_id" id="user_id" required>
            <option value="">-- Select user --</option>
            <?php foreach ($users as $user): ?>
                <option value="<?php echo htmlspecialchars($user['user_id']); ?>">
                    <?php echo htmlspecialchars($user['username']); ?>
                </option>
            <?php endforeach; ?>
        </select>
        
        <label for="asset_details">Assets Given to user (e.g., Laptop, Monitor, Phone):</label>
        <textarea name="asset_details" id="asset_details" rows="4" required placeholder="List assets, models, and serial numbers here..."></textarea>

        <div style="display: flex; gap: 20px;">
            <div style="flex: 1;">
                <label for="collection_date">Asset Collection Date:</label>
                <input type="date" name="collection_date" id="collection_date" required>
            
			<br/>
            
                <label for="return_date">Asset Returning Date (Optional - Leave blank if outstanding):</label>
                <input type="date" name="return_date" id="return_date">
            </div>
        </div>
        
        <button type="submit" name="add_asset">Save Asset Assignment</button>
    </form>
</div>

<!-- --- Asset List Button --- -->
<div class="form-card" style="margin-top: 30px;">
    <h3>Asset Log Database</h3>
    <p>View the complete history of all recorded asset assignments.</p>
    
    <button onclick="document.getElementById('assetDataModal').style.display='block'" 
           style="background-color: #2ecc71; color: white; padding: 15px 30px; border: none; border-radius: 8px; font-size: 16px; cursor: pointer;">
        View Full Asset List (<?php echo count($asset_data); ?> Records)
    </button>
</div>

<!-- Asset Data Modal (Popup Box) -->
<div id="assetDataModal" class="asset-modal">
    <div class="asset-modal-content">
        <span class="modal-close" onclick="document.getElementById('assetDataModal').style.display='none'">&times;</span>
        <h2>Full List of Assets</h2>
        <p>Assets currently outstanding are highlighted in light red.</p>

        <table class="data-table" style="width: 100%; border-collapse: collapse;">
            <thead>
                <tr>
                    <th>Record ID</th>
                    <th>Uer Name</th>
                    <th>Asset Details</th>
                    <th>Collection Date</th>
                    <th>Return Date</th>
                    <th>Status</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($asset_data)): ?>
                    <tr><td colspan="6" style="text-align: center;">No asset assignment records found.</td></tr>
                <?php else: ?>
                    <?php foreach ($asset_data as $asset): 
                        $is_pending = is_null($asset['return_date']);
                        $status_class = $is_pending ? 'asset-pending' : '';
                        $status_text = $is_pending ? 'OUTSTANDING' : 'RETURNED';
                    ?>
                    <tr class="<?php echo $status_class; ?>">
                        <td><?php echo htmlspecialchars($asset['asset_id']); ?></td>
                        <td><?php echo htmlspecialchars($asset['user_name']); ?></td>
                        <td><?php echo nl2br(htmlspecialchars($asset['asset_details'])); ?></td>
                        <td><?php echo htmlspecialchars($asset['collection_date']); ?></td>
                        <td><?php echo $is_pending ? 'N/A' : htmlspecialchars($asset['return_date']); ?></td>
                        <td style="font-weight: bold; color: <?php echo $is_pending ? '#c0392b' : '#27ae60'; ?>;"><?php echo $status_text; ?></td>
                    </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>
