<?php
require_once 'includes/db.php';
$machinery = fetchAll("SELECT * FROM machinery WHERE company_id = ? ORDER BY created_at DESC", [$_SESSION['company_id']]);
?>

<div style="display: flex; justify-content: space-between; align-items: center; gap: 1rem; margin-bottom: 2rem;">
    <div style="position: relative; flex: 1; max-width: 400px;">
        <i class="fas fa-search" style="position: absolute; left: 1rem; top: 50%; transform: translateY(-50%); color: var(--text-muted); opacity: 0.5;"></i>
        <input type="text" id="machinerySearch" class="form-control" placeholder="Search by name, model, or type..." style="padding-left: 2.75rem; border-radius: 50px; background: var(--bg-card); border: 1px solid var(--border); box-shadow: var(--shadow);">
    </div>
    <button class="btn btn-primary" onclick="openAddMachineModal()" style="border-radius: 12px; padding: 0.75rem 1.5rem;">
        <i class="fas fa-plus"></i> Add Machine
    </button>
</div>

<div class="data-grid">
    <?php foreach ($machinery as $machine): ?>
    <div class="data-card" style="border-top: 4px solid <?php echo $machine['is_active'] ? 'var(--primary)' : 'var(--text-muted)'; ?>; transition: all 0.3s; <?php echo !$machine['is_active'] ? 'filter: grayscale(1) opacity(0.6);' : ''; ?>">
        <div class="data-card-header">
            <div>
                <div style="font-size: 0.7rem; font-weight: 800; color: var(--primary); text-transform: uppercase; letter-spacing: 1px; margin-bottom: 0.25rem;">
                    <?php echo $machine['type'] ?: 'General Machinery'; ?>
                </div>
                <h3 style="font-size: 1.125rem; font-weight: 700; color: var(--text-main);"><?php echo $machine['name']; ?></h3>
                <div style="font-size: 0.8rem; color: var(--text-muted); font-family: monospace;">Model: <?php echo $machine['model_no']; ?></div>
            </div>
            <div class="toggle-switch <?php echo $machine['is_active'] ? 'active' : ''; ?>" onclick="toggleMachineActive(<?php echo $machine['id']; ?>, <?php echo $machine['is_active']; ?>)" style="cursor: pointer; z-index: 10; position: relative; filter: none !important; opacity: 1 !important;">
                <div style="width: 40px; height: 20px; background: <?php echo $machine['is_active'] ? 'var(--primary)' : 'var(--border)'; ?>; border-radius: 20px; position: relative; transition: all 0.3s;">
                    <div style="width: 14px; height: 14px; background: white; border-radius: 50%; position: absolute; top: 3px; left: <?php echo $machine['is_active'] ? '23px' : '3px'; ?>; transition: all 0.3s;"></div>
                </div>
            </div>
        </div>
        
        <div class="data-card-body" style="padding: 0.5rem 0;">
            <div style="background: var(--bg-dark); padding: 0.75rem 1rem; border-radius: 12px; display: flex; justify-content: space-between; align-items: center;">
                <div>
                    <div style="font-size: 0.7rem; color: var(--text-muted); text-transform: uppercase; font-weight: 700;">Operational Status</div>
                    <div style="font-weight: 700; color: <?php echo $machine['status'] === 'Operating' ? 'var(--success)' : 'var(--warning)'; ?>;">
                        <i class="fas <?php echo $machine['status'] === 'Operating' ? 'fa-check-circle' : 'fa-tools'; ?>"></i>
                        <?php echo $machine['status']; ?>
                    </div>
                </div>
                <i class="fas fa-industry fa-2x" style="opacity: 0.1; color: var(--primary);"></i>
            </div>
        </div>

        <div class="data-card-footer" style="padding-top: 1rem; border-top: 1px solid var(--border); margin-top: auto;">
            <button class="btn btn-sm" 
                    style="background: var(--bg-dark); border-radius: 8px; cursor: <?php echo $machine['is_active'] ? 'pointer' : 'not-allowed'; ?>; opacity: <?php echo $machine['is_active'] ? '1' : '0.5'; ?>;" 
                    onclick='<?php echo $machine['is_active'] ? "editMachine(" . htmlspecialchars(json_encode($machine), ENT_QUOTES) . ")" : "notify(\"Please enable the machine before editing.\", \"warning\")"; ?>'>
                <i class="fas fa-edit"></i> Edit
            </button>
            <button class="btn btn-sm" style="background: rgba(239, 68, 68, 0.1); color: var(--danger); border-radius: 8px;" onclick="deleteMachine(<?php echo $machine['id']; ?>)">
                <i class="fas fa-trash"></i>
            </button>
        </div>
    </div>
    <?php endforeach; ?>

    <?php if (empty($machinery)): ?>
    <div style="grid-column: 1 / -1; text-align: center; padding: 5rem; background: var(--bg-card); border-radius: 24px; border: 2px dashed var(--border);">
        <i class="fas fa-gears fa-4x" style="margin-bottom: 1.5rem; color: var(--text-muted); opacity: 0.3;"></i>
        <h3 style="color: var(--text-main);">No Machinery Registered</h3>
        <p style="color: var(--text-muted);">Register your factory equipment to track operations and assign to production lines.</p>
    </div>
    <?php endif; ?>
</div>

<!-- Machine Modal -->
<div id="machineModal" class="modal-overlay">
    <div class="modal-content" style="max-width: 500px;">
        <div class="modal-header">
            <h2 id="modalTitle">Add New Machine</h2>
            <button class="btn" style="background: none; color: var(--text-muted);" onclick="closeModal('machineModal')">
                <i class="fas fa-times"></i>
            </button>
        </div>
        <form id="machineForm">
            <input type="hidden" id="machine_id" name="id">
            <div class="modal-body">
                <div class="form-group">
                    <label class="form-label">Machine Name <span class="required-mark">*</span></label>
                    <input type="text" name="name" id="machine_name" class="form-control" placeholder="e.g. Olock Machine" required>
                </div>
                <div class="form-group">
                    <label class="form-label">Model Number <span class="required-mark">*</span></label>
                    <input type="text" name="model_no" id="machine_model" class="form-control" placeholder="e.g. M00234" required>
                </div>
                <div class="form-group">
                    <label class="form-label">Type / Category</label>
                    <input type="text" name="type" id="machine_type" class="form-control" placeholder="e.g. Sewing, Cutting, Finishing">
                </div>
                <div class="form-group">
                    <label class="form-label">Operational Status</label>
                    <select name="status" id="machine_status" class="form-control">
                        <option value="Operating">Operating</option>
                        <option value="Maintenance">Maintenance</option>
                        <option value="Broken">Broken</option>
                        <option value="Idle">Idle</option>
                    </select>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn" onclick="closeModal('machineModal')">Cancel</button>
                <button type="submit" class="btn btn-primary">Save Machine</button>
            </div>
        </form>
    </div>
</div>

<script>
async function openAddMachineModal() {
    document.getElementById('modalTitle').innerText = 'Add New Machine';
    document.getElementById('machineForm').reset();
    document.getElementById('machine_id').value = '';
    openModal('machineModal');
}

function editMachine(machine) {
    document.getElementById('modalTitle').innerText = 'Edit Machine';
    document.getElementById('machine_id').value = machine.id;
    document.getElementById('machine_name').value = machine.name;
    document.getElementById('machine_model').value = machine.model_no;
    document.getElementById('machine_type').value = machine.type || '';
    document.getElementById('machine_status').value = machine.status || 'Operating';
    openModal('machineModal');
}

document.getElementById('machineForm').addEventListener('submit', async (e) => {
    e.preventDefault();
    const formData = new FormData(e.target);
    const data = Object.fromEntries(formData.entries());
    data.action = 'save';
    
    try {
        const result = await apiCall('machinery', data);
        if (result.success) {
            notify(result.message, 'success');
            closeModal('machineModal');
            setTimeout(() => location.reload(), 500);
        } else {
            notify(result.message, 'error');
        }
    } catch (error) {
        notify('Failed to save machine', 'error');
    }
});

async function deleteMachine(id) {
    const confirmed = await confirmAction({
        title: 'Delete Machine',
        message: 'Are you sure you want to permanently delete this machine? This action cannot be undone if the machine is not assigned to any production lines.',
        confirmText: 'Delete Permanently'
    });
    
    if (!confirmed) return;
    
    try {
        const result = await apiCall('machinery', { id, action: 'delete' });
        if (result.success) {
            notify(result.message, 'success');
            setTimeout(() => location.reload(), 500);
        } else {
            notify(result.message, 'error');
        }
    } catch (error) {
        notify('Failed to delete machine', 'error');
    }
}

async function toggleMachineActive(id, current) {
    const next = current ? 0 : 1;
    try {
        const result = await apiCall('machinery', { id, is_active: next, action: 'toggle-status' });
        if (result.success) {
            location.reload();
        }
    } catch (error) {
        notify('Failed to update status', 'error');
    }
}

// Real-time Machinery Search
document.getElementById('machinerySearch').addEventListener('input', function(e) {
    const term = e.target.value.toLowerCase();
    const cards = document.querySelectorAll('.data-card');
    let hasResults = false;
    
    cards.forEach(card => {
        const name = card.querySelector('h3').innerText.toLowerCase();
        const model = card.querySelector('.data-card-header div div:nth-of-type(2)').innerText.toLowerCase();
        const type = card.querySelector('.data-card-header div div:nth-of-type(1)').innerText.toLowerCase();
        
        if (name.includes(term) || model.includes(term) || type.includes(term)) {
            card.style.display = 'flex';
            hasResults = true;
        } else {
            card.style.display = 'none';
        }
    });

    // Handle "No Results" state
    const grid = document.querySelector('.data-grid');
    let noResultsMsg = document.getElementById('noSearchMsg');
    
    if (!hasResults) {
        if (!noResultsMsg) {
            noResultsMsg = document.createElement('div');
            noResultsMsg.id = 'noSearchMsg';
            noResultsMsg.style.cssText = 'grid-column: 1 / -1; text-align: center; padding: 4rem; color: var(--text-muted);';
            noResultsMsg.innerHTML = `
                <i class="fas fa-search-minus fa-3x" style="margin-bottom: 1rem; opacity: 0.5;"></i>
                <h3>No matches found for "${e.target.value}"</h3>
                <p>Try checking the spelling or use a different search term.</p>
            `;
            grid.appendChild(noResultsMsg);
        } else {
            noResultsMsg.querySelector('h3').innerText = `No matches found for "${e.target.value}"`;
        }
    } else if (noResultsMsg) {
        noResultsMsg.remove();
    }
});
</script>
