<?php
session_start();
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../classes/Database.php';
require_once __DIR__ . '/../../classes/Logger.php';
require_once __DIR__ . '/../../classes/Inventory.php';


$database = new Database();
$conn = $database->getConnection();


$auth = new Auth($conn);


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

if ($_SESSION['role'] != 'admin' && $_SESSION['role'] != 'warehouse') {
    header('Location: /IMS/unauthorized.php');
    exit;
}


$logger = new Logger($conn, $_SESSION['user_id'], $_SESSION['username'], $_SESSION['role']);


$inventory = new Inventory($conn, $logger);
$item = null;
$error = '';
$success = '';


if (!isset($_GET['item_id']) && $_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: get_branch_inventory.php?error=No item ID provided');
    exit();
}


if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $item_id = filter_input(INPUT_POST, 'item_id', FILTER_SANITIZE_NUMBER_INT);
    $item_name = trim($_POST['item_name']);
    $item_details = trim($_POST['item_details'] ?? '');
    $unique_code = trim($_POST['unique_code']);
    $unit_price = filter_input(INPUT_POST, 'unit_price', FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
    $description = trim($_POST['description']);
    $brand = trim($_POST['brand']);
    $model = trim($_POST['model']);
	$category = trim($_POST['category']);
    $serial_number = trim($_POST['serial_number']);
    $warranty_months = filter_input(INPUT_POST, 'warranty_months', FILTER_SANITIZE_NUMBER_INT);
    $technical_specs = trim($_POST['technical_specs']);
    $condition_status = trim($_POST['condition_status']);
    $apply_to_all = isset($_POST['apply_to_all']) ? true : false;


    if (empty($item_name) || empty($unique_code) || $unit_price === false || $unit_price < 0) {
        $error = 'Item name, unique code, and valid unit price are required.';
    } else {
        $data = [
            'item_name' => $item_name,
            'item_details' => $item_details,
            'unique_code' => $unique_code,
            'unit_price' => $unit_price,
            'description' => $description,
            'brand' => $brand,
            'model' => $model,
            'serial_number' => $serial_number,
            'warranty_months' => $warranty_months,
			'category' => $category,
            'technical_specs' => $technical_specs,
            'condition_status' => $condition_status
        ];
        if ($inventory->updateItem($item_id, $data, $apply_to_all)) {
            $success = 'Item updated successfully.';

            header("Location: edit_item.php?item_id=$item_id&success=" . urlencode($success));
            exit();
        } else {
            $error = 'Error updating item: ' . htmlspecialchars($inventory->getLastError());
        }
    }
}


if (isset($_GET['item_id'])) {
    $item_id = filter_input(INPUT_GET, 'item_id', FILTER_SANITIZE_NUMBER_INT);
    $item = $inventory->getItemById($item_id);
    if (!$item) {
        $error = 'Item not found.';
    }
}
?>

<?php include __DIR__ . '/../../includes/header.php'; ?>
<style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            color: #333;
            line-height: 1.6;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }

        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            background: rgba(255, 255, 255, 0.95);
            padding: 20px 30px;
            border-radius: 15px;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
            backdrop-filter: blur(10px);
        }

        .back-btn {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            padding: 12px 20px;
            background: #6c757d;
            color: white;
            text-decoration: none;
            border-radius: 8px;
            font-weight: 500;
            transition: all 0.3s ease;
        }

        .back-btn:hover {
            background: #5a6268;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
        }

        .item-id-badge {
            background: linear-gradient(45deg, #667eea, #764ba2);
            color: white;
            padding: 8px 16px;
            border-radius: 20px;
            font-weight: 600;
            font-size: 14px;
        }

        .page-title {
            text-align: center;
            margin-bottom: 40px;
        }

        .page-title h1 {
            font-size: 2.5rem;
            font-weight: 700;
            color: white;
            margin-bottom: 10px;
            text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
        }

        .page-title p {
            color: rgba(255, 255, 255, 0.9);
            font-size: 1.1rem;
        }

        .alert {
            padding: 16px 20px;
            border-radius: 12px;
            margin-bottom: 25px;
            display: flex;
            align-items: center;
            gap: 12px;
            font-weight: 500;
            animation: slideIn 0.3s ease;
        }

        .alert-success {
            background: linear-gradient(45deg, #28a745, #20c997);
            color: white;
            border: none;
        }

        .alert-danger {
            background: linear-gradient(45deg, #dc3545, #e74c3c);
            color: white;
            border: none;
        }

        .form-container {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 20px;
            padding: 0;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.1);
            backdrop-filter: blur(10px);
            overflow: hidden;
        }

        .form-section {
            padding: 30px;
            border-bottom: 1px solid #e9ecef;
        }

        .form-section:last-child {
            border-bottom: none;
        }

        .section-header {
            display: flex;
            align-items: center;
            gap: 12px;
            margin-bottom: 25px;
            padding-bottom: 15px;
            border-bottom: 2px solid #f8f9fa;
        }

        .section-icon {
            width: 40px;
            height: 40px;
            background: linear-gradient(45deg, #667eea, #764ba2);
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 18px;
        }

        .section-title {
            font-size: 1.4rem;
            font-weight: 600;
            color: #2c3e50;
        }

        .section-description {
            color: #6c757d;
            font-size: 0.9rem;
            margin-top: 4px;
        }

        .form-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 25px;
        }

        .form-group {
            display: flex;
            flex-direction: column;
        }

        .form-group.full-width {
            grid-column: 1 / -1;
        }

        .form-label {
            font-weight: 600;
            color: #2c3e50;
            margin-bottom: 8px;
            display: flex;
            align-items: center;
            gap: 6px;
        }

        .required {
            color: #e74c3c;
        }

        .form-control {
            padding: 14px 16px;
            border: 2px solid #e9ecef;
            border-radius: 10px;
            font-size: 16px;
            transition: all 0.3s ease;
            background: white;
        }

        .form-control:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
            transform: translateY(-1px);
        }

        .form-control:invalid {
            border-color: #e74c3c;
        }

        textarea.form-control {
            resize: vertical;
            min-height: 100px;
        }

        .condition-select {
            position: relative;
        }

        .condition-badge {
            display: inline-block;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .condition-new { background: #28a745; color: white; }
        .condition-used { background: #ffc107; color: #212529; }
        .condition-refurbished { background: #17a2b8; color: white; }

        .checkbox-group {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 12px;
            border: 2px dashed #dee2e6;
        }

        .checkbox-wrapper {
            display: flex;
            align-items: flex-start;
            gap: 12px;
        }

        .checkbox-input {
            width: 20px;
            height: 20px;
            accent-color: #667eea;
        }

        .checkbox-label {
            font-weight: 500;
            color: #2c3e50;
            cursor: pointer;
        }

        .checkbox-description {
            color: #6c757d;
            font-size: 0.85rem;
            margin-top: 4px;
        }

        .form-actions {
            padding: 30px;
            background: #f8f9fa;
            display: flex;
            justify-content: flex-end;
            gap: 15px;
        }

        .btn {
            padding: 14px 28px;
            border: none;
            border-radius: 10px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }

        .btn-primary {
            background: linear-gradient(45deg, #667eea, #764ba2);
            color: white;
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(102, 126, 234, 0.3);
        }

        .btn-secondary {
            background: #6c757d;
            color: white;
        }

        .btn-secondary:hover {
            background: #5a6268;
            transform: translateY(-2px);
        }

        .btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none !important;
        }

        .loading-spinner {
            width: 20px;
            height: 20px;
            border: 2px solid rgba(255, 255, 255, 0.3);
            border-radius: 50%;
            border-top-color: white;
            animation: spin 1s ease-in-out infinite;
        }

        @keyframes spin {
            to { transform: rotate(360deg); }
        }

        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateY(-20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        @media (max-width: 768px) {
            .container {
                padding: 15px;
            }

            .header {
                flex-direction: column;
                gap: 15px;
                text-align: center;
            }

            .page-title h1 {
                font-size: 2rem;
            }

            .form-grid {
                grid-template-columns: 1fr;
            }

            .form-actions {
                flex-direction: column;
            }
        }

        .input-icon {
            color: #667eea;
            font-size: 14px;
        }

        .price-input {
            position: relative;
        }

        .price-input::before {
            content: '$';
            position: absolute;
            left: 16px;
            top: 50%;
            transform: translateY(-50%);
            color: #6c757d;
            font-weight: 600;
            z-index: 1;
        }

        .price-input .form-control {
            padding-left: 35px;
        }
    </style>

    <div class="container">

        <div class="header">
            <a href="get_branch_inventory.php" class="back-btn">
                <i class="fas fa-arrow-left"></i>
                Back to Inventory
            </a>
            <?php if ($item): ?>
                <div class="item-id-badge">
                    <i class="fas fa-box"></i>
                    ID: <?php echo htmlspecialchars($item['item_id']); ?>
                </div>
            <?php endif; ?>
        </div>


        <div class="page-title">
            <h1>Edit Inventory Item</h1>
            <p>Update item details and specifications with enhanced controls</p>
        </div>


        <?php if ($error): ?>
            <div class="alert alert-danger">
                <i class="fas fa-exclamation-circle"></i>
                <?php echo htmlspecialchars($error); ?>
            </div>
        <?php elseif (isset($_GET['success'])): ?>
            <div class="alert alert-success">
                <i class="fas fa-check-circle"></i>
                <?php echo htmlspecialchars($_GET['success']); ?>
            </div>
        <?php endif; ?>

        <?php if ($item): ?>
            <div class="form-container">
                <form method="POST" action="edit_item.php?item_id=<?php echo htmlspecialchars($item['item_id']); ?>" id="editForm">
                    <input type="hidden" name="item_id" value="<?php echo htmlspecialchars($item['item_id']); ?>">


                    <div class="form-section">
                        <div class="section-header">
                            <div class="section-icon">
                                <i class="fas fa-box"></i>
                            </div>
                            <div>
                                <div class="section-title">Basic Information</div>
                                <div class="section-description">Essential item details and identification</div>
                            </div>
                        </div>

                        <div class="form-grid">
                            <div class="form-group">
                                <label for="item_name" class="form-label">
                                    <i class="fas fa-tag input-icon"></i>
                                    Item Name <span class="required">*</span>
                                </label>
                                <input type="text" class="form-control" id="item_name" name="item_name"
                                       value="<?php echo htmlspecialchars($item['item_name']); ?>" required>
                            </div>

                            <div class="form-group">
                                <label for="unique_code" class="form-label">
                                    <i class="fas fa-fingerprint input-icon"></i>
                                    Unique Code <span class="required">*</span>
                                </label>
                                <input type="text" class="form-control" id="unique_code" name="unique_code"
                                       value="<?php echo htmlspecialchars($item['unique_code'] ?? ''); ?>" required>
                            </div>

                            <div class="form-group">
                                <label for="unit_price" class="form-label">
                                    <i class="fas fa-dollar-sign input-icon"></i>
                                    Unit Price <span class="required">*</span>
                                </label>
                                <div class="price-input">
                                    <input type="number" step="0.01" class="form-control" id="unit_price" name="unit_price"
                                           value="<?php echo htmlspecialchars($item['unit_price']); ?>" required>
                                </div>
                            </div>

                            <div class="form-group full-width">
                                <label for="item_details" class="form-label"><i class="fas fa-align-left input-icon"></i> Item Details</label>
                                <textarea class="form-control" id="item_details" name="item_details" rows="3"><?php echo htmlspecialchars($item['item_details'] ?? ''); ?></textarea>
                            </div>

                            <div class="form-group full-width">
                                <label for="description" class="form-label">
                                    <i class="fas fa-align-left input-icon"></i>
                                    Description
                                </label>
                                <textarea class="form-control" id="description" name="description" rows="3"><?php echo htmlspecialchars($item['description'] ?? ''); ?></textarea>
                            </div>
                        </div>
                    </div>


                    <div class="form-section">
                        <div class="section-header">
                            <div class="section-icon">
                                <i class="fas fa-info-circle"></i>
                            </div>
                            <div>
                                <div class="section-title">Product Details</div>
                                <div class="section-description">Brand, model, and identification information</div>
                            </div>
                        </div>

                        <div class="form-grid">
                            <div class="form-group">
                                <label for="brand" class="form-label">
                                    <i class="fas fa-building input-icon"></i>
                                    Brand
                                </label>
                                <input type="text" class="form-control" id="brand" name="brand"
                                       value="<?php echo htmlspecialchars($item['brand'] ?? ''); ?>">
                            </div>

                            <div class="form-group">
                                <label for="model" class="form-label">
                                    <i class="fas fa-barcode input-icon"></i>
                                    Model
                                </label>
                                <input type="text" class="form-control" id="model" name="model"
                                       value="<?php echo htmlspecialchars($item['model'] ?? ''); ?>">
                            </div>

                            <div class="form-group">
                                <label for="serial_number" class="form-label">
                                    <i class="fas fa-hashtag input-icon"></i>
                                    Serial Number
                                </label>
                                <input type="text" class="form-control" id="serial_number" name="serial_number"
                                       value="<?php echo htmlspecialchars($item['serial_number'] ?? ''); ?>">
                            </div>

                            <div class="form-group">
                                <label for="warranty_months" class="form-label">
                                    <i class="fas fa-shield-alt input-icon"></i>
                                    Category 
                                </label>
								<select name="category" id="category" onchange="toggleCategory()" class="form-control">
									 <?php
									 
										echo '<option value="' . htmlspecialchars($item['category'] ?? '') . '">' .
												 htmlspecialchars($item['category'] ?? '') . '</option>';
												 
												 
										$branchObj = new Inventory($conn);
										$branches = $branchObj->getAllCategories();
										while ($branch = $branches->fetch(PDO::FETCH_ASSOC)) {
											echo '<option value="' . htmlspecialchars($branch['category_name']) . '">' .
												 htmlspecialchars($branch['category_name']) . '</option>';
										}
										?>

									</select>
								</div>
							
							 <div class="form-group">
                                <label for="warranty_months" class="form-label">
                                    <i class="fas fa-shield-alt input-icon"></i>
                                    Warranty (Months)
                                </label>
                                <input type="number" class="form-control" id="warranty_months" name="warranty_months"
                                       value="<?php echo htmlspecialchars($item['warranty_months'] ?? ''); ?>">
                            </div>
                        </div>
                    </div>


                    <div class="form-section">
                        <div class="section-header">
                            <div class="section-icon">
                                <i class="fas fa-cogs"></i>
                            </div>
                            <div>
                                <div class="section-title">Technical Specifications</div>
                                <div class="section-description">Detailed technical information and condition status</div>
                            </div>
                        </div>

                        <div class="form-grid">
                            <div class="form-group full-width">
                                <label for="technical_specs" class="form-label">
                                    <i class="fas fa-list-ul input-icon"></i>
                                    Technical Specifications
                                </label>
                                <textarea class="form-control" id="technical_specs" name="technical_specs" rows="4"><?php echo htmlspecialchars($item['technical_specs'] ?? ''); ?></textarea>
                            </div>

                            <div class="form-group">
                                <label for="condition_status" class="form-label">
                                    <i class="fas fa-check-circle input-icon"></i>
                                    Condition Status
                                </label>
                                <select class="form-control" id="condition_status" name="condition_status">
                                    <option value="">Select Condition</option>
                                    <option value="New" <?php echo ($item['condition_status'] === 'New') ? 'selected' : ''; ?>>New</option>
                                    <option value="Used" <?php echo ($item['condition_status'] === 'Used') ? 'selected' : ''; ?>>Used</option>
                                    <option value="OPEN_BOX" <?php echo ($item['condition_status'] === 'OPEN_BOX') ? 'selected' : ''; ?>>Open Box</option>
                                </select>
                            </div>
                        </div>
                    </div>


                    <div class="form-section">
                        <div class="checkbox-group">
                            <div class="checkbox-wrapper">
                                <input type="checkbox" class="checkbox-input" id="apply_to_all" name="apply_to_all">
                                <div>
                                    <label class="checkbox-label" for="apply_to_all">
                                        Apply changes to all items with the same name
                                    </label>
                                    <div class="checkbox-description">
                                        This will update all inventory items that share the same name with these changes.
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>


                    <div class="form-actions">
                        <button type="button" class="btn btn-secondary" onclick="window.history.back()">
                            <i class="fas fa-times"></i>
                            Cancel
                        </button>
                        <button type="submit" class="btn btn-primary" id="submitBtn">
                            <i class="fas fa-save"></i>
                            Save Changes
                        </button>
                    </div>
                </form>
            </div>
        <?php endif; ?>
    </div>

    <script>

        document.addEventListener('DOMContentLoaded', function() {
            const form = document.getElementById('editForm');
            const submitBtn = document.getElementById('submitBtn');
            const requiredFields = form.querySelectorAll('[required]');


            requiredFields.forEach(field => {
                field.addEventListener('input', validateField);
                field.addEventListener('blur', validateField);
            });

            function validateField(e) {
                const field = e.target;
                const isValid = field.checkValidity();

                if (isValid) {
                    field.style.borderColor = '#28a745';
                } else {
                    field.style.borderColor = '#e74c3c';
                }
            }


            form.addEventListener('submit', function(e) {
                const itemName = document.getElementById('item_name').value.trim();
                const uniqueCode = document.getElementById('unique_code').value.trim();
                const unitPrice = parseFloat(document.getElementById('unit_price').value);

                if (!itemName || !uniqueCode || isNaN(unitPrice) || unitPrice < 0) {
                    e.preventDefault();
                    showAlert('Please fill in all required fields with valid values.', 'danger');
                    return;
                }


                submitBtn.disabled = true;
                submitBtn.innerHTML = '<div class="loading-spinner"></div> Saving...';
            });


            const conditionSelect = document.getElementById('condition_status');
            conditionSelect.addEventListener('change', function() {
                updateConditionBadge(this.value);
            });

            function updateConditionBadge(condition) {

                console.log('Condition updated to:', condition);
            }


            let saveTimeout;
            const formInputs = form.querySelectorAll('input, textarea, select');

            formInputs.forEach(input => {
                input.addEventListener('input', function() {
                    clearTimeout(saveTimeout);
                    saveTimeout = setTimeout(saveDraft, 2000);
                });
            });

            function saveDraft() {
                const formData = new FormData(form);
                const draftData = {};

                for (let [key, value] of formData.entries()) {
                    draftData[key] = value;
                }

                localStorage.setItem('edit_item_draft', JSON.stringify(draftData));
                showTemporaryMessage('Draft saved automatically', 'info');
            }


            const savedDraft = localStorage.getItem('edit_item_draft');
            if (savedDraft) {

                console.log('Draft available:', JSON.parse(savedDraft));
            }

            function showAlert(message, type) {
                const alertDiv = document.createElement('div');
                alertDiv.className = `alert alert-${type}`;
                alertDiv.innerHTML = `
                    <i class="fas fa-${type === 'danger' ? 'exclamation-circle' : 'info-circle'}"></i>
                    ${message}
                `;

                const container = document.querySelector('.container');
                const pageTitle = document.querySelector('.page-title');
                container.insertBefore(alertDiv, pageTitle.nextSibling);

                setTimeout(() => {
                    alertDiv.remove();
                }, 5000);
            }

            function showTemporaryMessage(message, type) {
                const messageDiv = document.createElement('div');
                messageDiv.style.cssText = `
                    position: fixed;
                    top: 20px;
                    right: 20px;
                    background: ${type === 'info' ? '#17a2b8' : '#28a745'};
                    color: white;
                    padding: 12px 20px;
                    border-radius: 8px;
                    z-index: 1000;
                    animation: slideIn 0.3s ease;
                `;
                messageDiv.textContent = message;

                document.body.appendChild(messageDiv);

                setTimeout(() => {
                    messageDiv.remove();
                }, 3000);
            }


            const priceInput = document.getElementById('unit_price');
            priceInput.addEventListener('blur', function() {
                const value = parseFloat(this.value);
                if (!isNaN(value)) {
                    this.value = value.toFixed(2);
                }
            });


            document.addEventListener('keydown', function(e) {
                if (e.ctrlKey && e.key === 's') {
                    e.preventDefault();
                    form.dispatchEvent(new Event('submit'));
                }
            });
        });
    </script>
<?php include __DIR__ . '/../../includes/footer.php'; ?>