<?php
require_once('../includes/functions.php');

if (!isset($_SESSION['user_id']) || $_SESSION['role'] != 'admin') {
    header("Location: ../login.php");
    exit();
}

// Load tools data
$toolsFile = DATA_DIR . 'tools.json';
$tools = [];
if (file_exists($toolsFile)) {
    $tools = json_decode(file_get_contents($toolsFile), true);
    if (!is_array($tools)) $tools = [];
}

// Handle add/edit/delete actions
$message = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_POST['action'])) {
        if ($_POST['action'] == 'add') {
            $newTool = [
                'id' => count($tools) > 0 ? max(array_column($tools, 'id')) + 1 : 1,
                'tool_name' => trim($_POST['tool_name']),
                'part_number' => trim($_POST['part_number']),
                'calibration_date' => $_POST['calibration_date'],
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s')
            ];
            $tools[] = $newTool;
            $message = "✅ Tool added successfully!";
        }
        elseif ($_POST['action'] == 'edit') {
            $id = intval($_POST['id']);
            foreach ($tools as &$tool) {
                if ($tool['id'] == $id) {
                    $tool['tool_name'] = trim($_POST['tool_name']);
                    $tool['part_number'] = trim($_POST['part_number']);
                    $tool['calibration_date'] = $_POST['calibration_date'];
                    $tool['updated_at'] = date('Y-m-d H:i:s');
                    $message = "✅ Tool updated successfully!";
                    break;
                }
            }
        }
        elseif ($_POST['action'] == 'recalibrate') {
            $id = intval($_POST['id']);
            $newDate = $_POST['new_calibration_date'];
            foreach ($tools as &$tool) {
                if ($tool['id'] == $id) {
                    $tool['calibration_date'] = $newDate;
                    $tool['updated_at'] = date('Y-m-d H:i:s');
                    $message = "✅ Calibration date updated!";
                    break;
                }
            }
        }
        file_put_contents($toolsFile, json_encode($tools, JSON_PRETTY_PRINT));
    }
}

// Handle delete via GET
if (isset($_GET['delete_id'])) {
    $deleteId = intval($_GET['delete_id']);
    $newTools = [];
    foreach ($tools as $tool) {
        if ($tool['id'] != $deleteId) $newTools[] = $tool;
    }
    $tools = $newTools;
    file_put_contents($toolsFile, json_encode($tools, JSON_PRETTY_PRINT));
    $message = "🗑️ Tool deleted successfully!";
}

// Sort tools by next calibration date (soonest first)
usort($tools, function($a, $b) {
    return strtotime($a['calibration_date']) - strtotime($b['calibration_date']);
});

// Helper to check if expiry is within 30 days
function isExpiringWithin30($date) {
    if (empty($date)) return false;
    $today = strtotime(date('Y-m-d'));
    $expiry = strtotime($date);
    $daysLeft = floor(($expiry - $today) / (60 * 60 * 24));
    return ($daysLeft <= 30 && $daysLeft >= 0);
}
?>
<?php include('../includes/header.php'); ?>
<style>
    .tool-table {
        width: 100%;
        border-collapse: collapse;
        background: white;
        border-radius: 16px;
        overflow: hidden;
    }
    .tool-table th {
        background: #f8efe5;
        color: #6b1d2f;
        padding: 12px;
        text-align: left;
    }
    .tool-table td {
        padding: 10px 12px;
        border-bottom: 1px solid #f0e2d0;
    }
    .expiring-soon {
        background-color: #f8d7da;
        color: #721c24;
        font-weight: bold;
    }
    .btn-sm {
        padding: 4px 8px;
        font-size: 0.75rem;
        margin: 2px;
    }
    .form-inline {
        display: flex;
        gap: 8px;
        flex-wrap: wrap;
        align-items: flex-end;
    }
    .form-group {
        margin-bottom: 12px;
    }
    .form-group label {
        font-size: 0.8rem;
        margin-bottom: 4px;
        display: block;
    }
    .edit-form {
        background: #fefcf8;
        padding: 12px;
        border-radius: 12px;
        margin-top: 8px;
        border: 1px solid #e2cfb3;
    }
</style>
<div class="sidebar">
    <h3>📋 Admin Console</h3>
    <a href="dashboard.php" class="btn">📊 Dashboard</a>
    <a href="add_user.php" class="btn">👤 Add Crew</a>
    <a href="manage_users.php" class="btn">📋 Crew List</a>
    <a href="employee_list.php" class="btn">📋 Full Employee Data</a>
    <a href="edit_user.php" class="btn">✏️ Edit Crew</a>
    <a href="manage_endorsements.php" class="btn">✈️ Endorsements</a>
    <a href="add_memo.php" class="btn">📝 New Memo</a>
    <a href="add_quiz.php" class="btn">📚 New Quiz</a>
    <a href="inbox.php" class="btn">📥 Safety Reports</a>
    <a href="chat.php" class="btn">💬 Group Chat</a>
    <a href="tools.php" class="btn active">🔧 Tools Management</a>
    <a href="upload_manual.php" class="btn">📘 Upload Manual</a>
</div>
<div class="content">
    <h2>🔧 Tooling & Calibration Management</h2>
    
    <?php if($message): ?>
        <div class="alert alert-success"><?php echo $message; ?></div>
    <?php endif; ?>
    
    <!-- Add New Tool Form -->
    <div class="card">
        <h3>➕ Add New Tool</h3>
        <form method="POST">
            <input type="hidden" name="action" value="add">
            <div class="form-inline">
                <div class="form-group" style="flex:2;">
                    <label>Tool Name</label>
                    <input type="text" name="tool_name" required placeholder="e.g., Torque Wrench">
                </div>
                <div class="form-group" style="flex:1;">
                    <label>Part Number</label>
                    <input type="text" name="part_number" placeholder="e.g., TW-100">
                </div>
                <div class="form-group" style="flex:1;">
                    <label>Calibration Due Date</label>
                    <input type="date" name="calibration_date" required>
                </div>
                <div class="form-group">
                    <button type="submit" class="btn btn-primary">➕ Add Tool</button>
                </div>
            </div>
        </form>
    </div>
    
    <!-- Tools List -->
    <div class="card">
        <h3>📋 Tool Inventory</h3>
        <?php if(empty($tools)): ?>
            <p>No tools added yet.</p>
        <?php else: ?>
            <div class="table-responsive">
                <table class="tool-table">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Tool Name</th>
                            <th>Part Number</th>
                            <th>Calibration Due</th>
                            <th>Status</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach($tools as $tool): 
                            $expiring = isExpiringWithin30($tool['calibration_date']);
                            $rowClass = $expiring ? 'expiring-soon' : '';
                        ?>
                            <tr class="<?php echo $rowClass; ?>">
                                <td>#<?php echo $tool['id']; ?></td>
                                <td><?php echo htmlspecialchars($tool['tool_name']); ?></td>
                                <td><?php echo htmlspecialchars($tool['part_number'] ?: '-'); ?></td>
                                <td><?php echo date('M j, Y', strtotime($tool['calibration_date'])); ?></td>
                                <td>
                                    <?php if($expiring): ?>
                                        <strong>⚠️ Expires within 30 days!</strong>
                                    <?php else: ?>
                                        ✓ OK
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <!-- Edit button triggers inline edit form -->
                                    <button class="btn btn-sm" onclick="toggleEditForm(<?php echo $tool['id']; ?>)">✏️ Edit</button>
                                    <a href="?delete_id=<?php echo $tool['id']; ?>" class="btn btn-sm" style="background:#a03e4b; color:white;" onclick="return confirm('Delete this tool?')">🗑️ Delete</a>
                                    <!-- Quick recalibrate (update date) -->
                                    <form method="POST" style="display:inline;">
                                        <input type="hidden" name="action" value="recalibrate">
                                        <input type="hidden" name="id" value="<?php echo $tool['id']; ?>">
                                        <input type="date" name="new_calibration_date" style="width:120px; padding:4px;">
                                        <button type="submit" class="btn btn-sm">🔄 Update Date</button>
                                    </form>
                                </td>
                            </tr>
                            <!-- Inline edit row (hidden by default) -->
                            <tr id="edit-row-<?php echo $tool['id']; ?>" style="display:none; background:#faf3e8;">
                                <td colspan="6">
                                    <div class="edit-form">
                                        <form method="POST">
                                            <input type="hidden" name="action" value="edit">
                                            <input type="hidden" name="id" value="<?php echo $tool['id']; ?>">
                                            <div class="form-inline">
                                                <div class="form-group" style="flex:2;">
                                                    <label>Tool Name</label>
                                                    <input type="text" name="tool_name" value="<?php echo htmlspecialchars($tool['tool_name']); ?>" required>
                                                </div>
                                                <div class="form-group" style="flex:1;">
                                                    <label>Part Number</label>
                                                    <input type="text" name="part_number" value="<?php echo htmlspecialchars($tool['part_number']); ?>">
                                                </div>
                                                <div class="form-group" style="flex:1;">
                                                    <label>Calibration Due Date</label>
                                                    <input type="date" name="calibration_date" value="<?php echo $tool['calibration_date']; ?>" required>
                                                </div>
                                                <div class="form-group">
                                                    <button type="submit" class="btn btn-success">💾 Save</button>
                                                    <button type="button" class="btn" onclick="toggleEditForm(<?php echo $tool['id']; ?>)">Cancel</button>
                                                </div>
                                            </div>
                                        </form>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </div>
</div>

<script>
    function toggleEditForm(id) {
        var row = document.getElementById('edit-row-' + id);
        if (row.style.display === 'none') {
            row.style.display = 'table-row';
        } else {
            row.style.display = 'none';
        }
    }
</script>

<div class="clearfix"></div>
<?php include('../includes/footer.php'); ?>