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

// Check if $conn exists (safety check, typically handled by dashboard)
if (!isset($conn)) {
    if (file_exists('config/db_connection.php')) {
        require_once 'config/db_connection.php';
    } else {
        // Fallback or error message if required file is missing
        echo "<div class='alert alert-error'>FATAL ERROR: Database connection configuration file not found.</div>";
        exit();
    }
}

$status_message = '';
$users = []; // Array to store user names for the dropdown
$current_date = date('Y-m-d'); // Current date for status comparison

// --- HELPER FUNCTION: Determine Asset Status (Feature 3) ---
function get_asset_status($collection_date, $return_date, $created_at) {
    $today = date('Y-m-d');
    
    // Status Logic
    if (!empty($return_date)) {
        // Returned date is present
        $return_ts = strtotime($return_date);
        $collection_ts = strtotime($collection_date);

        // Check if return date is on or after collection date
        if ($return_ts >= $collection_ts) {
            return 'WELL RETURNED'; // Returned successfully
        } else {
            // This scenario implies an invalid date record, but for simplicity, we'll mark as returned.
            return 'RETURNED (DATE ERROR)';
        }
    } else {
        // No return date (Outstanding)
        $collection_ts = strtotime($collection_date);
        
        if ($collection_ts > strtotime($today)) {
             // Future collection date (Shouldn't happen with current input, but safety check)
             return 'PENDING ASSIGNMENT';
        }

        // If collection date is in the past or today, it is Assigned.
        // We assume the original logic intended to track if an asset is OVERDUE based on some criteria.
        // Since there is no DUE DATE provided in the DB, we will use the collection date + 30 days as a simple overdue trigger.
        $due_date = date('Y-m-d', strtotime($collection_date . ' + 30 days'));

        if ($today > $due_date) {
            return 'NOT RETURNED'; // Overdue based on arbitrary 30-day period
        } else {
            return 'ASSIGNED'; // Currently assigned and not overdue
        }
    }
}

// --- 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 (Feature 1, 2) ---
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['add_asset'])) {
    
    // Get and sanitize input
    $user_id = (int)($_POST['user_id'] ?? 0);
    $collection_date = trim($_POST['collection_date'] ?? '');
    $asset_details_array = $_POST['asset_details'] ?? [];
    $return_date_array = $_POST['return_date'] ?? [];
    $permanent_array = $_POST['permanent'] ?? [];

    $has_error = false;
    $new_records = 0;

    if (empty($user_id) || empty($collection_date) || empty($asset_details_array)) {
        $status_message = "<div class='alert alert-error'>User, Collection Date, and at least one Asset Detail are required.</div>";
        $has_error = true;
    } else {
        // Process each dynamic asset row
        foreach ($asset_details_array as $index => $details) {
            $details = trim($details);
            $current_return_date = trim($return_date_array[$index] ?? '');
            $is_permanent = isset($permanent_array[$index]);

            // Validation: Asset Details required and length check
            if (empty($details)) {
                $status_message = "<div class='alert alert-error'>Error: Asset Detail field cannot be empty (Row " . ($index + 1) . ").</div>";
                $has_error = true;
                break;
            }
            if (strlen($details) > 25) {
                 $status_message = "<div class='alert alert-error'>Error: Asset Detail max character limit (25) exceeded (Row " . ($index + 1) . ").</div>";
                $has_error = true;
                break;
            }
            
            // Validation (Feature 2): Must have either a return date OR permanent flag
            if (empty($current_return_date) && !$is_permanent) {
                $status_message = "<div class='alert alert-error'>Error: Asset (Row " . ($index + 1) . ") must have a Return Date OR the 'Untill remains as employee' box checked.</div>";
                $has_error = true;
                break;
            }
            
            // Set final return date value for DB
            // If permanent, set return_date to null in the DB, as the asset is outstanding indefinitely.
            $db_return_date = $is_permanent ? null : ($current_return_date ?: null);
            
            // Prepare and execute individual INSERT
            $sql = "INSERT INTO assets (user_id, asset_details, collection_date, return_date) VALUES (?, ?, ?, ?)";
            $stmt = $conn->prepare($sql);
            
            if ($stmt) {
                $stmt->bind_param("isss", $user_id, $details, $collection_date, $db_return_date);
                if ($stmt->execute()) {
                    $new_records++;
                } else {
                    $status_message = "<div class='alert alert-error'>Database insert failed for asset '{$details}': " . $stmt->error . "</div>";
                    $has_error = true;
                    break;
                }
                $stmt->close();
            } else {
                $status_message = "<div class='alert alert-error'>Database prepare error: " . $conn->error . "</div>";
                $has_error = true;
                break;
            }
        }
    }
    
    if (!$has_error && $new_records > 0) {
        $status_message = "<div class='alert alert-info'>Success! {$new_records} asset record(s) created successfully.</div>";
    }
}

// --- D. Logic for Updating Asset Status (Feature 4) ---
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['update_asset_status'])) {
    $asset_id = (int)$_POST['update_asset_id'];
    $new_return_date = trim($_POST['new_return_date']);

    if (empty($asset_id) || empty($new_return_date)) {
        $status_message = "<div class='alert alert-error'>Error: Asset ID and a valid Return Date are required for update.</div>";
    } else {
        $sql = "UPDATE assets SET return_date = ? WHERE asset_id = ?";
        $stmt = $conn->prepare($sql);
        
        if ($stmt) {
            $stmt->bind_param("si", $new_return_date, $asset_id);
            if ($stmt->execute()) {
                $status_message = "<div class='alert alert-info'>Success! Asset ID {$asset_id} status updated to RETURNED on {$new_return_date}.</div>";
            } else {
                $status_message = "<div class='alert alert-error'>Error updating asset record: " . $stmt->error . "</div>";
            }
            $stmt->close();
        } else {
            $status_message = "<div class='alert alert-error'>Database prepare error for update: " . $conn->error . "</div>";
        }
    }
}


// --- 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()) {
        // Calculate status using the new logic (Feature 3)
        $row['status'] = get_asset_status($row['collection_date'], $row['return_date'], $row['created_at']);
        $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);
        justify-content: center; /* Center content horizontally */
        align-items: center; /* Center content vertically */
    }
    .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;
    }
    /* Feature 3 Status Styling */
    .status-assigned { background-color: #d8edf2; } /* Light blue */
    .status-well-returned { background-color: #e6ffe6; color: #155724; font-weight: bold; } /* Light green */
    .status-not-returned { background-color: #fcebeb; color: #c0392b; font-weight: bold; } /* Light red */
    
    /* Dynamic Form Styling (Feature 1, 2) */
    .asset-row {
        display: grid;
        grid-template-columns: 2fr 1fr 1fr 40px; /* Details | Date | Checkbox | Remove Button */
        gap: 10px;
        align-items: center;
        margin-bottom: 10px;
        border: 1px solid #eee;
        padding: 10px;
        border-radius: 4px;
    }
    .asset-row input[type="text"] {
        max-width: 100%;
        box-sizing: border-box;
    }
    .asset-row label {
        display: block;
        white-space: nowrap;
    }
    .asset-row .permanent-check {
        display: flex;
        align-items: center;
        gap: 5px;
    }
    .asset-row .remove-btn {
        background: #e74c3c;
        color: white;
        border: none;
        padding: 8px;
        border-radius: 4px;
        cursor: pointer;
        height: 35px;
        line-height: 1;
    }
    .add-btn {
        background: #2ecc71;
        color: white;
        border: none;
        padding: 10px 15px;
        border-radius: 4px;
        cursor: pointer;
        margin-top: 10px;
    }
    .alert-info { background-color: #d9edf7; color: #31708f; padding: 10px; border-radius: 4px; margin-bottom: 15px; }
    .alert-error { background-color: #f2dede; color: #a94442; padding: 10px; border-radius: 4px; margin-bottom: 15px; }
</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. **Max 25 characters per asset detail.**</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>
        
        <div style="display: flex; gap: 20px; margin-bottom: 15px;">
            <div style="flex: 1;">
                <label for="collection_date">Asset Collection Date:</label>
                <input type="date" name="collection_date" id="collection_date" required value="<?php echo date('Y-m-d'); ?>">
            </div>
        </div>
        
        <!-- --- Dynamic Asset Input Fields (Feature 1, 2) --- -->
        <h4 style="margin-top: 10px; margin-bottom: 5px;">Individual Asset Records:</h4>
        <p style="font-size: 0.9em; color: #7f8c8d;">Must include a Return Date or mark as permanent.</p>
        
        <div id="asset-container">
            <!-- Template Asset Row -->
            <div class="asset-row">
                <div>
                    <label for="asset_details_0">Asset Details (Max 25 chars):</label>
                    <input type="text" name="asset_details[]" id="asset_details_0" maxlength="25" required>
                </div>
                <div>
                    <label for="return_date_0">Target Return Date:</label>
                    <input type="date" name="return_date[]" id="return_date_0" min="<?php echo date('Y-m-d'); ?>">
                </div>
                <div class="permanent-check">
                    <input type="checkbox" name="permanent[0]" id="permanent_0" value="1" onchange="toggleReturnDate(0)">
                    <label for="permanent_0" style="display: inline;">Untill remains as employee</label>
                </div>
                <div>
                    <!-- Remove button for first row is typically disabled/hidden if min 1 is required, but we'll include it for dynamic additions -->
                </div>
            </div>
        </div>
        
        <button type="button" class="add-btn" onclick="addAssetRow()">+ Add Another Asset</button>

        <button type="submit" name="add_asset" style="margin-top: 20px;">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='flex'" 
            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>Use the **Update** button to record a return date for an outstanding asset.</p>

        <table class="data-table" style="width: 100%; border-collapse: collapse;">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>User Name</th>
                    <th>Asset Details</th>
                    <th>Collection Date</th>
                    <th>Target Return Date</th>
                    <th>Status</th>
                    <th style="width: 150px; text-align: center;">Action (Feature 4)</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($asset_data)): ?>
                    <tr><td colspan="7" style="text-align: center;">No asset assignment records found.</td></tr>
                <?php else: ?>
                    <?php foreach ($asset_data as $asset): 
                        $status = $asset['status'];
                        $status_class = 'status-' . strtolower(str_replace(' ', '-', $status));
                        $display_return_date = empty($asset['return_date']) ? 'N/A' : htmlspecialchars($asset['return_date']);
                    ?>
                    <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 $display_return_date; ?></td>
                        <td style="font-weight: bold;"><?php echo $status; ?></td>
                        <td style="text-align: center;">
                            <?php if ($status !== 'WELL RETURNED' && $status !== 'RETURNED (DATE ERROR)'): ?>
                                <button onclick="promptForReturn(<?php echo $asset['asset_id']; ?>)" 
                                        style="background-color: #f39c12; color: white; border: none; padding: 8px; border-radius: 4px; cursor: pointer;">
                                    Update Return
                                </button>
                            <?php else: ?>
                                Complete
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<script>
    let assetRowIndex = 1;
    const assetContainer = document.getElementById('asset-container');

    // Function to handle the permanent checkbox/return date logic
    function toggleReturnDate(index) {
        const returnDateInput = document.getElementById(`return_date_${index}`);
        const permanentCheckbox = document.getElementById(`permanent_${index}`);
        
        if (permanentCheckbox.checked) {
            returnDateInput.value = '';
            returnDateInput.disabled = true;
            returnDateInput.required = false;
        } else {
            returnDateInput.disabled = false;
            returnDateInput.required = true;
        }
    }

    // Function to add a new dynamic asset row (Feature 1)
    function addAssetRow() {
        const newRow = document.createElement('div');
        newRow.className = 'asset-row';
        newRow.innerHTML = `
            <div>
                <label for="asset_details_${assetRowIndex}">Asset Details (Max 25 chars):</label>
                <input type="text" name="asset_details[]" id="asset_details_${assetRowIndex}" maxlength="25" required>
            </div>
            <div>
                <label for="return_date_${assetRowIndex}">Target Return Date:</label>
                <input type="date" name="return_date[]" id="return_date_${assetRowIndex}" required min="<?php echo date('Y-m-d'); ?>">
            </div>
            <div class="permanent-check">
                <input type="checkbox" name="permanent[${assetRowIndex}]" id="permanent_${assetRowIndex}" value="1" onchange="toggleReturnDate(${assetRowIndex})">
                <label for="permanent_${assetRowIndex}" style="display: inline;">Untill remains as employee</label>
            </div>
            <div>
                <button type="button" class="remove-btn" onclick="this.closest('.asset-row').remove()">X</button>
            </div>
        `;
        assetContainer.appendChild(newRow);
        assetRowIndex++;
    }

    // Function to prompt for return update (Feature 4)
    function promptForReturn(assetId) {
        const today = new Date().toISOString().split('T')[0];
        let returnDate = prompt(`Enter the actual return date for Asset ID ${assetId}:`, today);

        if (returnDate) {
            // Basic date format validation
            if (!/^\d{4}-\d{2}-\d{2}$/.test(returnDate)) {
                alert("Invalid date format. Please use YYYY-MM-DD.");
                return;
            }

            // Create a temporary form to submit the update
            const form = document.createElement('form');
            form.method = 'POST';
            form.action = 'admin_dashboard.php?page=manage_assets';

            const idInput = document.createElement('input');
            idInput.type = 'hidden';
            idInput.name = 'update_asset_id';
            idInput.value = assetId;

            const dateInput = document.createElement('input');
            dateInput.type = 'hidden';
            dateInput.name = 'new_return_date';
            dateInput.value = returnDate;

            const actionInput = document.createElement('input');
            actionInput.type = 'hidden';
            actionInput.name = 'update_asset_status';
            actionInput.value = '1';

            form.appendChild(idInput);
            form.appendChild(dateInput);
            form.appendChild(actionInput);
            document.body.appendChild(form);
            
            // Submit the form to trigger the PHP update logic
            form.submit();
        }
    }
</script>
