@extends('layouts.app')

@section('title', 'Edit Customer')
@section('page-title', 'Edit Customer')

@section('content')
<div class="card">
    <div class="card-header">
        <h5 class="mb-0">Edit Customer</h5>
    </div>
    <div class="card-body">
        <form action="{{ route('partner.customers.update', $customer) }}" method="POST" enctype="multipart/form-data" id="customerForm">
            @csrf
            @method('PUT')
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label for="photo" class="form-label">Customer Photo</label>
                    @if($customer->photo)
                        <div class="mb-2">
                            <img src="{{ Storage::url($customer->photo) }}" alt="Current Photo" 
                                 style="width: 150px; height: 150px; object-fit: cover; border-radius: 8px; border: 2px solid var(--border-color);">
                        </div>
                        <div class="mb-2">
                            <label class="form-check-label">
                                <input type="checkbox" name="remove_photo" value="1" class="form-check-input" id="remove_photo_check">
                                Remove current photo
                            </label>
                        </div>
                    @endif
                    <div class="mb-2">
                        <input type="file" class="form-control @error('photo') is-invalid @enderror" 
                               id="photo" name="photo" accept="image/*">
                        <small class="text-muted">Max 50KB, will be auto-cropped to 1:1 ratio</small>
                        @error('photo')
                            <div class="invalid-feedback">{{ $message }}</div>
                        @enderror
                    </div>
                    <!-- Photo Preview and Crop Area -->
                    <div id="photoPreview" style="display: none;" class="mb-3">
                        <div class="mb-2">
                            <img id="photoPreviewImg" src="" alt="Preview" style="max-width: 100%; max-height: 400px;">
                        </div>
                        <div class="d-flex gap-2">
                            <button type="button" class="btn btn-sm btn-primary" id="cropPhotoBtn">Crop Photo</button>
                            <button type="button" class="btn btn-sm btn-secondary" id="cancelCropBtn">Cancel</button>
                        </div>
                    </div>
                    <!-- Cropped Image Display -->
                    <div id="croppedPreview" style="display: none;" class="mb-3">
                        <div class="mb-2">
                            <img id="croppedImg" src="" alt="Cropped" style="width: 150px; height: 150px; object-fit: cover; border-radius: 8px; border: 2px solid var(--border-color);">
                        </div>
                        <button type="button" class="btn btn-sm btn-danger" id="removePhotoBtn">Remove New Photo</button>
                    </div>
                    <input type="hidden" name="photo_crop_data" id="photo_crop_data">
                </div>
                <div class="col-md-6 mb-3">
                    <label for="name" class="form-label">Name *</label>
                    <input type="text" class="form-control @error('name') is-invalid @enderror" 
                           id="name" name="name" value="{{ old('name', $customer->name) }}" required>
                    @error('name')
                        <div class="invalid-feedback">{{ $message }}</div>
                    @enderror
                </div>
                <div class="col-md-6 mb-3">
                    <label for="phone" class="form-label">Phone *</label>
                    <input type="text" class="form-control @error('phone') is-invalid @enderror" 
                           id="phone" name="phone" value="{{ old('phone', $customer->phone) }}" required>
                    @error('phone')
                        <div class="invalid-feedback">{{ $message }}</div>
                    @enderror
                </div>
            </div>
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label for="email" class="form-label">Email</label>
                    <input type="email" class="form-control" id="email" name="email" value="{{ old('email', $customer->email) }}">
                </div>
                <div class="col-md-6 mb-3">
                    <label for="date_of_birth" class="form-label">Date of Birth</label>
                    <input type="date" class="form-control" id="date_of_birth" name="date_of_birth" value="{{ old('date_of_birth', $customer->date_of_birth?->format('Y-m-d')) }}">
                </div>
            </div>
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label for="gender" class="form-label">Gender</label>
                    <select class="form-select" id="gender" name="gender">
                        <option value="">Select</option>
                        <option value="male" {{ old('gender', $customer->gender) === 'male' ? 'selected' : '' }}>Male</option>
                        <option value="female" {{ old('gender', $customer->gender) === 'female' ? 'selected' : '' }}>Female</option>
                        <option value="other" {{ old('gender', $customer->gender) === 'other' ? 'selected' : '' }}>Other</option>
                    </select>
                </div>
                <div class="col-md-6 mb-3">
                    <label for="status" class="form-label">Status *</label>
                    <select class="form-select" id="status" name="status" required>
                        <option value="active" {{ old('status', $customer->status) === 'active' ? 'selected' : '' }}>Active</option>
                        <option value="inactive" {{ old('status', $customer->status) === 'inactive' ? 'selected' : '' }}>Inactive</option>
                    </select>
                </div>
            </div>
            <div class="mb-3">
                <label for="address" class="form-label">Address</label>
                <textarea class="form-control" id="address" name="address" rows="3">{{ old('address', $customer->address) }}</textarea>
            </div>
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label for="id_proof_type" class="form-label">ID Proof Type</label>
                    <input type="text" class="form-control" id="id_proof_type" name="id_proof_type" value="{{ old('id_proof_type', $customer->id_proof_type) }}">
                </div>
                <div class="col-md-6 mb-3">
                    <label for="id_proof_number" class="form-label">ID Proof Number</label>
                    <input type="text" class="form-control" id="id_proof_number" name="id_proof_number" value="{{ old('id_proof_number', $customer->id_proof_number) }}">
                </div>
            </div>
            <div class="d-flex gap-2">
                <button type="submit" class="btn btn-primary">
                    <i class="bi bi-save"></i> Update Customer
                </button>
                <a href="{{ route('partner.customers.index') }}" class="btn btn-secondary">Cancel</a>
            </div>
        </form>
    </div>
</div>

<!-- Cropper.js CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/cropperjs@1.6.2/dist/cropper.min.css">

@section('scripts')
<!-- Cropper.js JS -->
<script src="https://cdn.jsdelivr.net/npm/cropperjs@1.6.2/dist/cropper.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    const photoInput = document.getElementById('photo');
    const photoPreview = document.getElementById('photoPreview');
    const photoPreviewImg = document.getElementById('photoPreviewImg');
    const croppedPreview = document.getElementById('croppedPreview');
    const croppedImg = document.getElementById('croppedImg');
    const photoCropData = document.getElementById('photo_crop_data');
    const cropPhotoBtn = document.getElementById('cropPhotoBtn');
    const cancelCropBtn = document.getElementById('cancelCropBtn');
    const removePhotoBtn = document.getElementById('removePhotoBtn');
    const removePhotoCheck = document.getElementById('remove_photo_check');
    let cropper = null;

    // Handle file selection
    photoInput.addEventListener('change', function(e) {
        const file = e.target.files[0];
        if (file) {
            // Uncheck remove photo if uploading new one
            if (removePhotoCheck) {
                removePhotoCheck.checked = false;
            }

            // Check file size (5MB max)
            if (file.size > 5 * 1024 * 1024) {
                alert('File size must be less than 5MB');
                photoInput.value = '';
                return;
            }

            const reader = new FileReader();
            reader.onload = function(e) {
                photoPreviewImg.src = e.target.result;
                photoPreview.style.display = 'block';
                croppedPreview.style.display = 'none';
                
                // Initialize cropper with 1:1 aspect ratio
                if (cropper) {
                    cropper.destroy();
                }
                cropper = new Cropper(photoPreviewImg, {
                    aspectRatio: 1,
                    viewMode: 1,
                    autoCropArea: 0.8,
                    responsive: true,
                    guides: true,
                    center: true,
                    highlight: false,
                    cropBoxMovable: true,
                    cropBoxResizable: true,
                });
            };
            reader.readAsDataURL(file);
        }
    });

    // Crop button
    cropPhotoBtn.addEventListener('click', function() {
        if (cropper) {
            const canvas = cropper.getCroppedCanvas({
                width: 500,
                height: 500,
                imageSmoothingEnabled: true,
                imageSmoothingQuality: 'high',
            });

            // Convert to base64
            const base64 = canvas.toDataURL('image/jpeg', 0.9);
            photoCropData.value = base64;
            
            // Show cropped preview
            croppedImg.src = base64;
            croppedPreview.style.display = 'block';
            photoPreview.style.display = 'none';
            
            // Clear file input
            photoInput.value = '';
            
            // Destroy cropper
            if (cropper) {
                cropper.destroy();
                cropper = null;
            }
        }
    });

    // Cancel crop
    cancelCropBtn.addEventListener('click', function() {
        photoPreview.style.display = 'none';
        photoInput.value = '';
        if (cropper) {
            cropper.destroy();
            cropper = null;
        }
    });

    // Remove new photo
    removePhotoBtn.addEventListener('click', function() {
        croppedPreview.style.display = 'none';
        photoCropData.value = '';
        photoInput.value = '';
        if (cropper) {
            cropper.destroy();
            cropper = null;
        }
    });

    // Handle remove photo checkbox
    if (removePhotoCheck) {
        removePhotoCheck.addEventListener('change', function() {
            if (this.checked) {
                photoInput.value = '';
                photoCropData.value = '';
                croppedPreview.style.display = 'none';
                photoPreview.style.display = 'none';
                if (cropper) {
                    cropper.destroy();
                    cropper = null;
                }
            }
        });
    }
});
</script>
@endsection

