@extends('layouts.navigation')

<style>
    :root {
        --primary-color: #0a9a73;
        --secondary-color: #2c3e50;
        --sidebar-bg: #1e272e;
    }

    body {
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        background: #f8f9fa;
    }

    /* Main Content */
    .main-content {
        margin-left: 260px;
        padding: 0;
        min-height: 100vh;
    }

    /* Top Navigation */
    .top-nav {
        background: white;
        padding: 20px 30px;
        box-shadow: 0 2px 10px rgba(0,0,0,0.05);
        display: flex;
        justify-content: space-between;
        align-items: center;
        position: sticky;
        top: 0;
        z-index: 999;
    }

    .top-nav h2 {
        color: var(--secondary-color);
        margin: 0;
        font-size: 28px;
        font-weight: 600;
    }

    .user-profile {
        display: flex;
        align-items: center;
        gap: 15px;
    }

    .user-info {
        text-align: right;
    }

    .user-name {
        font-weight: 600;
        color: var(--secondary-color);
        font-size: 14px;
    }

    .user-role {
        font-size: 12px;
        color: #7f8c8d;
    }

    .logout-btn {
        background: rgba(231, 76, 60, 0.1);
        color: #e74c3c;
        border: none;
        padding: 10px 20px;
        border-radius: 8px;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.3s;
    }

    .logout-btn:hover {
        background: #e74c3c;
        color: white;
    }

    /* Page Content */
    .page-content {
        padding: 30px;
    }

    /* Card Styles */
    .card {
        border: none;
        border-radius: 12px;
        box-shadow: 0 0 20px rgba(0,0,0,0.08);
        margin-bottom: 30px;
    }

    .card-header {
        background: var(--primary-color);
        color: white;
        border: none;
        border-radius: 12px 12px 0 0 !important;
        padding: 20px 25px;
        font-weight: 600;
        font-size: 18px;
    }

    .card-body {
        padding: 25px;
    }

    /* Form Styles */
    .form-label {
        font-weight: 600;
        color: var(--secondary-color);
        margin-bottom: 8px;
    }

    .form-control, .form-select {
        border-radius: 8px;
        border: 2px solid #e9ecef;
        padding: 12px 15px;
        transition: all 0.3s;
    }

    .form-control:focus, .form-select:focus {
        border-color: var(--primary-color);
        box-shadow: 0 0 0 0.2rem rgba(10, 154, 115, 0.15);
    }

    .btn-primary {
        background: var(--primary-color);
        border: none;
        padding: 12px 30px;
        border-radius: 8px;
        font-weight: 600;
        transition: all 0.3s;
    }

    .btn-primary:hover {
        background: #087d5d;
        transform: translateY(-2px);
        box-shadow: 0 5px 15px rgba(10, 154, 115, 0.3);
    }

    .btn-secondary {
        background: #6c757d;
        border: none;
        padding: 12px 30px;
        border-radius: 8px;
        font-weight: 600;
        transition: all 0.3s;
    }

    /* Image Upload Preview */
    .image-preview-container {
        display: flex;
        flex-wrap: wrap;
        gap: 10px;
        margin-top: 10px;
    }

    .image-preview {
        position: relative;
        width: 100px;
        height: 100px;
        border: 2px solid #e9ecef;
        border-radius: 8px;
        overflow: hidden;
    }

    .image-preview img {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }

    .remove-image {
        position: absolute;
        top: 5px;
        right: 5px;
        background: rgba(231, 76, 60, 0.9);
        color: white;
        border: none;
        border-radius: 50%;
        width: 25px;
        height: 25px;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 12px;
    }

    .remove-image:hover {
        background: #e74c3c;
    }

    /* Existing Images Display */
    .existing-images {
        display: flex;
        flex-wrap: wrap;
        gap: 10px;
        margin-bottom: 15px;
    }

    .existing-image {
        position: relative;
        width: 100px;
        height: 100px;
        border: 2px solid #0a9a73;
        border-radius: 8px;
        overflow: hidden;
    }

    .existing-image img {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }

    .delete-existing-image {
        position: absolute;
        top: 5px;
        right: 5px;
        background: rgba(231, 76, 60, 0.9);
        color: white;
        border: none;
        border-radius: 50%;
        width: 25px;
        height: 25px;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 12px;
    }

    /* Table Styles */
    .table {
        margin: 0;
    }

    .table thead th {
        background: #f8f9fa;
        color: var(--secondary-color);
        font-weight: 600;
        border: none;
        padding: 15px;
        font-size: 14px;
        text-transform: uppercase;
        letter-spacing: 0.5px;
    }

    .table tbody td {
        padding: 15px;
        vertical-align: middle;
        border-bottom: 1px solid #f1f3f5;
    }

    .table tbody tr:hover {
        background: #f8f9fa;
    }

    /* Product Images in Table */
    .product-images {
        display: flex;
        gap: 5px;
    }

    .product-thumb {
        width: 50px;
        height: 50px;
        border-radius: 6px;
        object-fit: cover;
        border: 2px solid #e9ecef;
    }

    .more-images {
        width: 50px;
        height: 50px;
        border-radius: 6px;
        background: #f8f9fa;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 12px;
        font-weight: 600;
        color: #6c757d;
    }

    /* Badge Styles */
    .badge {
        padding: 8px 15px;
        border-radius: 20px;
        font-weight: 600;
        font-size: 12px;
    }

    .badge-success {
        background: rgba(39, 174, 96, 0.1);
        color: #27ae60;
    }

    .badge-danger {
        background: rgba(231, 76, 60, 0.1);
        color: #e74c3c;
    }

    .badge-warning {
        background: rgba(243, 156, 18, 0.1);
        color: #f39c12;
    }

    /* Price Display */
    .price-display {
        display: flex;
        flex-direction: column;
        gap: 3px;
    }

    .original-price {
        text-decoration: line-through;
        color: #95a5a6;
        font-size: 12px;
    }

    .discount-price {
        color: #e74c3c;
        font-weight: 600;
    }

    .regular-price {
        color: var(--primary-color);
        font-weight: 600;
    }

    /* Action Buttons */
    .btn-action {
        padding: 8px 15px;
        border-radius: 6px;
        font-size: 14px;
        border: none;
        cursor: pointer;
        transition: all 0.3s;
        margin-right: 5px;
    }

    .btn-edit {
        background: rgba(52, 152, 219, 0.1);
        color: #3498db;
    }

    .btn-edit:hover {
        background: #3498db;
        color: white;
    }

    .btn-delete {
        background: rgba(231, 76, 60, 0.1);
        color: #e74c3c;
    }

    .btn-delete:hover {
        background: #e74c3c;
        color: white;
    }

    /* Alert Styles */
    .alert {
        border: none;
        border-radius: 10px;
        padding: 15px 20px;
        margin-bottom: 20px;
    }

    .alert-success {
        background: rgba(39, 174, 96, 0.1);
        color: #27ae60;
        border-left: 4px solid #27ae60;
    }

    .alert-danger {
        background: rgba(231, 76, 60, 0.1);
        color: #e74c3c;
        border-left: 4px solid #e74c3c;
    }

    /* Empty State */
    .empty-state {
        text-align: center;
        padding: 60px 20px;
        color: #95a5a6;
    }

    .empty-state i {
        font-size: 64px;
        margin-bottom: 20px;
        opacity: 0.5;
    }

    .empty-state h4 {
        margin-bottom: 10px;
        color: #7f8c8d;
    }

    /* Responsive */
    @media (max-width: 768px) {
        .main-content {
            margin-left: 0;
        }
    }
</style>

@section('content')

<!-- Main Content -->
<div class="main-content">
    <!-- Top Navigation -->
    <div class="top-nav">
        <h2><i class="fas fa-pills"></i> Product Management</h2>

        <div class="user-profile">
            <div class="user-info">
                <div class="user-name">{{ auth()->user()->name }}</div>
                <div class="user-role">Administrator</div>
            </div>
            <img src="https://ui-avatars.com/api/?name={{ urlencode(auth()->user()->name) }}&background=0a9a73&color=fff" alt="User" style="width: 45px; height: 45px; border-radius: 50%; border: 2px solid var(--primary-color);">
            <form method="POST" action="{{ route('logout') }}" style="margin: 0;">
                @csrf
                <button type="submit" class="logout-btn">
                    <i class="fas fa-sign-out-alt"></i> Logout
                </button>
            </form>
        </div>
    </div>

    <!-- Page Content -->
    <div class="page-content">

        <!-- Success/Error Messages -->
        @if(session('success'))
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <i class="fas fa-check-circle"></i> {{ session('success') }}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        @endif

        @if(session('error'))
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <i class="fas fa-exclamation-circle"></i> {{ session('error') }}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        @endif

        <div class="row">
            <!-- Add/Edit Product Form -->
            <div class="col-lg-4">
                <div class="card">
                    <div class="card-header">
                        <i class="fas fa-{{ isset($product) ? 'edit' : 'plus-circle' }}"></i>
                        {{ isset($product) ? 'Edit Product' : 'Add New Product' }}
                    </div>
                    <div class="card-body">
                        @if(isset($product))
                            <!-- Edit Form -->
                            <form method="POST" action="{{ route('admin.products.update', $product) }}" enctype="multipart/form-data">
                                @csrf
                                @method('PUT')

                                <!-- Category -->
                                <div class="mb-3">
                                    <label for="category_id" class="form-label">Category *</label>
                                    <select class="form-select @error('category_id') is-invalid @enderror"
                                            id="category_id"
                                            name="category_id"
                                            required>
                                        <option value="">Select Category</option>
                                        @foreach($categories as $cat)
                                            <option value="{{ $cat->id }}" {{ old('category_id', $product->category_id) == $cat->id ? 'selected' : '' }}>
                                                {{ $cat->name }}
                                            </option>
                                        @endforeach
                                    </select>
                                    @error('category_id')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>

                                <!-- Product Name -->
                                <div class="mb-3">
                                    <label for="name" class="form-label">Product Name *</label>
                                    <input type="text"
                                           class="form-control @error('name') is-invalid @enderror"
                                           id="name"
                                           name="name"
                                           value="{{ old('name', $product->name) }}"
                                           placeholder="e.g., Antiseptic Spray"
                                           required>
                                    @error('name')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>

                                <!-- Price -->
                                <div class="mb-3">
                                    <label for="price" class="form-label">Price ($) *</label>
                                    <input type="number"
                                           class="form-control @error('price') is-invalid @enderror"
                                           id="price"
                                           name="price"
                                           value="{{ old('price', $product->price) }}"
                                           step="0.01"
                                           min="0"
                                           placeholder="99.99"
                                           required>
                                    @error('price')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>

                                <!-- Discount Price -->
                                <div class="mb-3">
                                    <label for="discount_price" class="form-label">Discount Price ($)</label>
                                    <input type="number"
                                           class="form-control @error('discount_price') is-invalid @enderror"
                                           id="discount_price"
                                           name="discount_price"
                                           value="{{ old('discount_price', $product->discount_price) }}"
                                           step="0.01"
                                           min="0"
                                           placeholder="79.99">
                                    @error('discount_price')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                    <small class="text-muted">Leave empty if no discount</small>
                                </div>

                                <!-- Existing Images -->
                                @if($product->images->count() > 0)
                                    <div class="mb-3">
                                        <label class="form-label">Current Images</label>
                                        <div class="existing-images">
                                            @foreach($product->images as $image)
                                                <div class="existing-image" id="image-{{ $image->id }}">
                                                    <img src="{{ asset('storage/' . $image->image) }}" alt="Product Image">
                                                    <button type="button"
                                                            class="delete-existing-image"
                                                            onclick="deleteImage({{ $image->id }})"
                                                            {{ $product->images->count() <= 1 ? 'disabled' : '' }}>
                                                        <i class="fas fa-times"></i>
                                                    </button>
                                                </div>
                                            @endforeach
                                        </div>
                                        <small class="text-muted">Click X to remove an image (minimum 1 required)</small>
                                    </div>
                                @endif

                                <!-- Add More Images -->
                                <div class="mb-3">
                                    <label for="images" class="form-label">Add More Images</label>
                                    <input type="file"
                                           class="form-control @error('images.*') is-invalid @enderror"
                                           id="images"
                                           name="images[]"
                                           accept="image/*"
                                           multiple
                                           onchange="previewImages(event)">
                                    @error('images.*')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                    <small class="text-muted">Select multiple images (Max 2MB each)</small>
                                    <div id="imagePreview" class="image-preview-container"></div>
                                </div>

                                <div class="d-grid gap-2">
                                    <button type="submit" class="btn btn-primary">
                                        <i class="fas fa-save"></i> Update Product
                                    </button>
                                    <a href="{{ route('admin.products.index') }}" class="btn btn-secondary">
                                        <i class="fas fa-times"></i> Cancel
                                    </a>
                                </div>
                            </form>
                        @else
                            <!-- Add Form -->
                            <form method="POST" action="{{ route('admin.products.store') }}" enctype="multipart/form-data">
                                @csrf

                                <!-- Category -->
                                <div class="mb-3">
                                    <label for="category_id" class="form-label">Category *</label>
                                    <select class="form-select @error('category_id') is-invalid @enderror"
                                            id="category_id"
                                            name="category_id"
                                            required>
                                        <option value="">Select Category</option>
                                        @foreach($categories as $cat)
                                            <option value="{{ $cat->id }}" {{ old('category_id') == $cat->id ? 'selected' : '' }}>
                                                {{ $cat->name }}
                                            </option>
                                        @endforeach
                                    </select>
                                    @error('category_id')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>

                                <!-- Product Name -->
                                <div class="mb-3">
                                    <label for="name" class="form-label">Product Name *</label>
                                    <input type="text"
                                           class="form-control @error('name') is-invalid @enderror"
                                           id="name"
                                           name="name"
                                           value="{{ old('name') }}"
                                           placeholder="e.g., Antiseptic Spray"
                                           required
                                           autofocus>
                                    @error('name')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>

                                <!-- Price -->
                                <div class="mb-3">
                                    <label for="price" class="form-label">Price ($) *</label>
                                    <input type="number"
                                           class="form-control @error('price') is-invalid @enderror"
                                           id="price"
                                           name="price"
                                           value="{{ old('price') }}"
                                           step="0.01"
                                           min="0"
                                           placeholder="99.99"
                                           required>
                                    @error('price')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>

                                <!-- Discount Price -->
                                <div class="mb-3">
                                    <label for="discount_price" class="form-label">Discount Price ($)</label>
                                    <input type="number"
                                           class="form-control @error('discount_price') is-invalid @enderror"
                                           id="discount_price"
                                           name="discount_price"
                                           value="{{ old('discount_price') }}"
                                           step="0.01"
                                           min="0"
                                           placeholder="79.99">
                                    @error('discount_price')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                    <small class="text-muted">Leave empty if no discount</small>
                                </div>

                                <!-- Product Images -->
                                <div class="mb-3">
                                    <label for="images" class="form-label">Product Images * (Min 1)</label>
                                    <input type="file"
                                           class="form-control @error('images') is-invalid @enderror"
                                           id="images"
                                           name="images[]"
                                           accept="image/*"
                                           multiple
                                           required
                                           onchange="previewImages(event)">
                                    @error('images')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                    @error('images.*')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                    <small class="text-muted">Select multiple images (Max 2MB each)</small>
                                    <div id="imagePreview" class="image-preview-container"></div>
                                </div>

                                <div class="d-grid">
                                    <button type="submit" class="btn btn-primary">
                                        <i class="fas fa-plus-circle"></i> Add Product
                                    </button>
                                </div>
                            </form>
                        @endif
                    </div>
                </div>

                <!-- Quick Stats -->
                <div class="card">
                    <div class="card-header">
                        <i class="fas fa-chart-bar"></i> Quick Stats
                    </div>
                    <div class="card-body">
                        <div class="d-flex justify-content-between mb-3">
                            <span class="text-muted">Total Products:</span>
                            <strong class="text-primary">{{ $products->count() }}</strong>
                        </div>
                        <div class="d-flex justify-content-between">
                            <span class="text-muted">Total Categories:</span>
                            <strong class="text-success">{{ $categories->count() }}</strong>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Products Table -->
            <div class="col-lg-8">
                <div class="card">
                    <div class="card-header">
                        <i class="fas fa-table"></i> All Products ({{ $products->count() }})
                    </div>
                    <div class="card-body p-0">
                        @if($products->count() > 0)
                            <div class="table-responsive">
                                <table class="table table-hover mb-0">
                                    <thead>
                                        <tr>
                                            <th width="5%">#</th>
                                            <th width="15%">Images</th>
                                            <th width="25%">Product</th>
                                            <th width="15%">Category</th>
                                            <th width="15%">Price</th>
                                            <th width="15%" class="text-center">Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        @foreach($products as $index => $prod)
                                            <tr>
                                                <td>{{ $index + 1 }}</td>
                                                <td>
                                                    <div class="product-images">
                                                        @if($prod->images->count() > 0)
                                                            <img src="{{ asset('storage/' . $prod->images->first()->image) }}"
                                                                 alt="{{ $prod->name }}"
                                                                 class="product-thumb">
                                                            @if($prod->images->count() > 1)
                                                                <div class="more-images">
                                                                    +{{ $prod->images->count() - 1 }}
                                                                </div>
                                                            @endif
                                                        @else
                                                            <div class="more-images">No Image</div>
                                                        @endif
                                                    </div>
                                                </td>
                                                <td>
                                                    <strong>{{ $prod->name }}</strong>
                                                </td>
                                                <td>
                                                    <strong class=" ">{{ $prod->category->name }}</strong>
                                                </td>
                                                <td>
                                                    <div class="price-display">
                                                        @if($prod->is_on_sale)
                                                            <span class="original-price">${{ number_format($prod->price, 2) }}</span>
                                                            <span class="discount-price">${{ number_format($prod->discount_price, 2) }}</span>
                                                            <span class="badge badge-danger">-{{ $prod->discount_percentage }}%</span>
                                                        @else
                                                            <span class="regular-price">${{ number_format($prod->price, 2) }}</span>
                                                        @endif
                                                    </div>
                                                </td>
                                                <td class="text-center">
                                                    <!-- Edit Button -->
                                                    {{-- <a href="{{ route('admin.products.edit', $prod) }}"
                                                       class="btn-action btn-edit"
                                                       title="Edit">
                                                        <i class="fas fa-edit"></i>
                                                    </a> --}}

                                                    <!-- Delete Button -->
                                                    <form action="{{ route('admin.products.destroy', $prod) }}"
                                                          method="POST"
                                                          style="display: inline;"
                                                          onsubmit="return confirm('Are you sure you want to delete this product and all its images?');">
                                                        @csrf
                                                        @method('DELETE')
                                                        <button type="submit"
                                                                class="btn-action btn-delete"
                                                                title="Delete">
                                                            <i class="fas fa-trash"></i>
                                                        </button>
                                                    </form>
                                                </td>
                                            </tr>
                                        @endforeach
                                    </tbody>
                                </table>
                            </div>
                        @else
                            <div class="empty-state">
                                <i class="fas fa-pills"></i>
                                <h4>No Products Yet</h4>
                                <p>Create your first product using the form on the left.</p>
                            </div>
                        @endif
                    </div>
                </div>
            </div>
        </div>

    </div>
</div>

<!-- JavaScript for Image Preview -->
<script>
    // Preview selected images before upload
    function previewImages(event) {
        const preview = document.getElementById('imagePreview');
        preview.innerHTML = '';

        const files = event.target.files;

        for (let i = 0; i < files.length; i++) {
            const file = files[i];
            const reader = new FileReader();

            reader.onload = function(e) {
                const div = document.createElement('div');
                div.className = 'image-preview';
                div.innerHTML = `
                    <img src="${e.target.result}" alt="Preview">
                `;
                preview.appendChild(div);
            }

            reader.readAsDataURL(file);
        }
    }

    // Delete existing image (AJAX)
    function deleteImage(imageId) {
        if (!confirm('Are you sure you want to delete this image?')) {
            return;
        }

        fetch(`/admin/products/images/${imageId}`, {
            method: 'DELETE',
            headers: {
                'X-CSRF-TOKEN': '{{ csrf_token() }}',
                'Accept': 'application/json',
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                document.getElementById(`image-${imageId}`).remove();
                alert('Image deleted successfully!');
            } else {
                alert(data.message || 'Error deleting image');
            }
        })
        .catch(error => {
            alert('Error deleting image');
            console.error('Error:', error);
        });
    }

    // Auto-hide alerts after 5 seconds
    setTimeout(function() {
        var alerts = document.querySelectorAll('.alert');
        alerts.forEach(function(alert) {
            var bsAlert = new bootstrap.Alert(alert);
            bsAlert.close();
        });
    }, 5000);
</script>

@endsection
