<?php
require_once '../connection.php';

// Check if user is admin
if (!isAdmin()) {
    header('Location: ../login.php');
    exit();
}

// Handle deletion
if (isset($_GET['delete'])) {
    $id = $_GET['delete'];
    
    try {
        // Get images to delete files
        $stmt = $pdo->prepare("SELECT image_url FROM laptop_images WHERE laptop_id = ?");
        $stmt->execute([$id]);
        $images = $stmt->fetchAll();
        
        // Delete image files
        foreach ($images as $image) {
            $file_path = '../' . $image['image_url'];
            if (file_exists($file_path)) {
                unlink($file_path);
            }
        }
        
        // Delete from database (cascade will delete images)
        $stmt = $pdo->prepare("DELETE FROM laptops WHERE id = ?");
        $stmt->execute([$id]);
        
        $_SESSION['success'] = "Laptop deleted successfully!";
    } catch (Exception $e) {
        $_SESSION['error'] = "Error deleting laptop: " . $e->getMessage();
    }
    
    header('Location: laptops.php');
    exit();
}

// Get all laptops
$stmt = $pdo->query("
    SELECT l.*, c.name as category_name,
           (SELECT image_url FROM laptop_images WHERE laptop_id = l.id AND is_primary = 1 LIMIT 1) as primary_image
    FROM laptops l 
    LEFT JOIN laptop_categories c ON l.category_id = c.id 
    ORDER BY l.created_at DESC
");
$laptops = $stmt->fetchAll();

// Get categories for filter
$categories = $pdo->query("SELECT * FROM laptop_categories WHERE is_active = 1")->fetchAll();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Laptops - Admin Panel</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <link href="https://cdn.datatables.net/1.11.5/css/dataTables.bootstrap5.min.css" rel="stylesheet">
    <style>
        .laptop-image {
            width: 60px;
            height: 60px;
            object-fit: cover;
            border-radius: 5px;
        }
        .status-badge {
            padding: 5px 10px;
            border-radius: 5px;
            font-size: 12px;
        }
        .status-active {
            background: #d4edda;
            color: #155724;
        }
        .status-inactive {
            background: #f8d7da;
            color: #721c24;
        }
        .action-buttons .btn {
            margin: 2px;
        }
    </style>
</head>
<body>
    <nav class="navbar navbar-dark bg-dark">
        <div class="container-fluid">
            <span class="navbar-brand">Admin Panel - Manage Laptops</span>
            <div>
                <a href="dashboard.php" class="btn btn-outline-light btn-sm">Dashboard</a>
                <a href="../logout.php" class="btn btn-outline-light btn-sm">Logout</a>
            </div>
        </div>
    </nav>

    <div class="container mt-4">
        <!-- Success/Error Messages -->
        <?php if(isset($_SESSION['success'])): ?>
            <div class="alert alert-success alert-dismissible fade show">
                <?php 
                    echo $_SESSION['success'];
                    unset($_SESSION['success']);
                ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>
        
        <?php if(isset($_SESSION['error'])): ?>
            <div class="alert alert-danger alert-dismissible fade show">
                <?php 
                    echo $_SESSION['error'];
                    unset($_SESSION['error']);
                ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <div class="card">
            <div class="card-header bg-primary text-white d-flex justify-content-between align-items-center">
                <h4 class="mb-0"><i class="fas fa-laptop"></i> Laptops Management</h4>
                <button class="btn btn-light" data-bs-toggle="modal" data-bs-target="#addLaptopModal">
                    <i class="fas fa-plus"></i> Add New Laptop
                </button>
            </div>
            <div class="card-body">
                <table id="laptopsTable" class="table table-bordered table-striped">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Image</th>
                            <th>Brand</th>
                            <th>Model</th>
                            <th>Category</th>
                            <th>Price</th>
                            <th>Stock</th>
                            <th>Status</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach($laptops as $laptop): ?>
                        <tr>
                            <td><?php echo $laptop['id']; ?></td>
                            <td>
                                <?php if($laptop['primary_image']): ?>
                                    <img src="../<?php echo $laptop['primary_image']; ?>" class="laptop-image" alt="Laptop">
                                <?php else: ?>
                                    <i class="fas fa-laptop fa-2x text-muted"></i>
                                <?php endif; ?>
                            </td>
                            <td><?php echo htmlspecialchars($laptop['brand']); ?></td>
                            <td><?php echo htmlspecialchars($laptop['model']); ?></td>
                            <td><?php echo htmlspecialchars($laptop['category_name']); ?></td>
                            <td>$<?php echo number_format($laptop['price'], 2); ?></td>
                            <td><?php echo $laptop['stock_quantity']; ?></td>
                            <td>
                                <span class="status-badge <?php echo $laptop['is_active'] ? 'status-active' : 'status-inactive'; ?>">
                                    <?php echo $laptop['is_active'] ? 'Active' : 'Inactive'; ?>
                                </span>
                            </td>
                            <td class="action-buttons">
                                <button class="btn btn-sm btn-info" onclick="editLaptop(<?php echo $laptop['id']; ?>)">
                                    <i class="fas fa-edit"></i> Edit
                                </button>
                                <button class="btn btn-sm btn-warning" onclick="manageImages(<?php echo $laptop['id']; ?>)">
                                    <i class="fas fa-images"></i> Images
                                </button>
                                <button class="btn btn-sm btn-danger" onclick="deleteLaptop(<?php echo $laptop['id']; ?>, '<?php echo addslashes($laptop['brand'] . ' ' . $laptop['model']); ?>')">
                                    <i class="fas fa-trash"></i> Delete
                                </button>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Add Laptop Modal -->
    <div class="modal fade" id="addLaptopModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header bg-primary text-white">
                    <h5 class="modal-title"><i class="fas fa-plus"></i> Add New Laptop</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <form action="add_laptop.php" method="POST" enctype="multipart/form-data">
                    <div class="modal-body">
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Brand *</label>
                                <input type="text" name="brand" class="form-control" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Model *</label>
                                <input type="text" name="model" class="form-control" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Category *</label>
                                <select name="category_id" class="form-control" required>
                                    <option value="">Select Category</option>
                                    <?php foreach($categories as $cat): ?>
                                        <option value="<?php echo $cat['id']; ?>"><?php echo htmlspecialchars($cat['name']); ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Condition *</label>
                                <select name="condition" class="form-control" required>
                                    <option value="new">New</option>
                                    <option value="refurbished">Refurbished</option>
                                    <option value="used">Used</option>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Processor</label>
                                <input type="text" name="processor" class="form-control" placeholder="e.g., Intel Core i7-12700H">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">RAM</label>
                                <input type="text" name="ram" class="form-control" placeholder="e.g., 16GB DDR4">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Storage</label>
                                <input type="text" name="storage" class="form-control" placeholder="e.g., 512GB NVMe SSD">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Display</label>
                                <input type="text" name="display" class="form-control" placeholder="e.g., 15.6\" FHD 144Hz">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Graphics</label>
                                <input type="text" name="graphics" class="form-control" placeholder="e.g., NVIDIA RTX 3060">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Battery</label>
                                <input type="text" name="battery" class="form-control" placeholder="e.g., 4-cell, 52.5 Wh">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Operating System</label>
                                <input type="text" name="os" class="form-control" placeholder="e.g., Windows 11 Pro">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Warranty</label>
                                <input type="text" name="warranty" class="form-control" placeholder="e.g., 1 Year">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Price ($) *</label>
                                <input type="number" name="price" class="form-control" step="0.01" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Discount Price ($)</label>
                                <input type="number" name="discount_price" class="form-control" step="0.01">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Stock Quantity</label>
                                <input type="number" name="stock_quantity" class="form-control" value="1">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Featured Product</label>
                                <select name="is_featured" class="form-control">
                                    <option value="0">No</option>
                                    <option value="1">Yes</option>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Status</label>
                                <select name="is_active" class="form-control">
                                    <option value="1">Active</option>
                                    <option value="0">Inactive</option>
                                </select>
                            </div>
                            <div class="col-12 mb-3">
                                <label class="form-label">Primary Image</label>
                                <input type="file" name="primary_image" class="form-control" accept="image/*" required>
                                <small class="text-muted">Main product image (will be displayed first)</small>
                            </div>
                            <div class="col-12 mb-3">
                                <label class="form-label">Additional Images</label>
                                <input type="file" name="additional_images[]" class="form-control" accept="image/*" multiple>
                                <small class="text-muted">You can select multiple images for gallery</small>
                            </div>
                            <div class="col-12 mb-3">
                                <label class="form-label">Description</label>
                                <textarea name="description" class="form-control" rows="3"></textarea>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">Add Laptop</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Edit Laptop Modal -->
    <div class="modal fade" id="editLaptopModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header bg-info text-white">
                    <h5 class="modal-title"><i class="fas fa-edit"></i> Edit Laptop</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <div id="editLaptopContent">
                    <div class="text-center p-5">
                        <div class="spinner-border text-primary"></div>
                        <p>Loading...</p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Manage Images Modal -->
    <div class="modal fade" id="manageImagesModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header bg-warning text-dark">
                    <h5 class="modal-title"><i class="fas fa-images"></i> Manage Images</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div id="manageImagesContent">
                    <div class="text-center p-5">
                        <div class="spinner-border text-primary"></div>
                        <p>Loading...</p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.11.5/js/dataTables.bootstrap5.min.js"></script>
    <script>
        $(document).ready(function() {
            $('#laptopsTable').DataTable({
                order: [[0, 'desc']],
                pageLength: 25
            });
        });

        function editLaptop(id) {
            $('#editLaptopModal').modal('show');
            $('#editLaptopContent').html('<div class="text-center p-5"><div class="spinner-border text-primary"></div><p>Loading...</p></div>');
            
            $.ajax({
                url: 'edit_laptop.php',
                type: 'GET',
                data: { id: id },
                success: function(response) {
                    $('#editLaptopContent').html(response);
                },
                error: function() {
                    $('#editLaptopContent').html('<div class="alert alert-danger m-3">Failed to load laptop data</div>');
                }
            });
        }

        function manageImages(id) {
            $('#manageImagesModal').modal('show');
            $('#manageImagesContent').html('<div class="text-center p-5"><div class="spinner-border text-primary"></div><p>Loading...</p></div>');
            
            $.ajax({
                url: 'manage_images.php',
                type: 'GET',
                data: { id: id },
                success: function(response) {
                    $('#manageImagesContent').html(response);
                },
                error: function() {
                    $('#manageImagesContent').html('<div class="alert alert-danger m-3">Failed to load images</div>');
                }
            });
        }

        function deleteLaptop(id, name) {
            if (confirm('Are you sure you want to delete "' + name + '"?\nThis action cannot be undone!')) {
                window.location.href = 'laptops.php?delete=' + id;
            }
        }
    </script>
</body>
</html>