@extends('admin.layouts.app')
@section('title', 'Vendor: '.$vendor->business_name)
@section('content')
<div class="page-header d-print-none">
    <div class="container-xl">
        <div class="row g-2 align-items-center">
            <div class="col-auto"><a href="{{ route('admin.vendors.index') }}" class="btn btn-outline-secondary btn-sm">← Back</a></div>
            <div class="col"><h2 class="page-title">{{ $vendor->business_name }}</h2></div>
            <div class="col-auto d-flex gap-2">
                @if($vendor->status === 'pending')
                    <form action="{{ route('admin.vendors.approve', $vendor) }}" method="POST">@csrf<button class="btn btn-success btn-sm">Approve</button></form>
                    <button class="btn btn-danger btn-sm" data-bs-toggle="modal" data-bs-target="#rejectModal">Reject</button>
                @elseif($vendor->status === 'active')
                    <button class="btn btn-warning btn-sm" data-bs-toggle="modal" data-bs-target="#suspendModal">Suspend</button>
                @elseif($vendor->status === 'suspended')
                    <form action="{{ route('admin.vendors.reactivate', $vendor) }}" method="POST">@csrf<button class="btn btn-success btn-sm">Reactivate</button></form>
                @endif
            </div>
        </div>
    </div>
</div>
<div class="page-body">
    <div class="row g-4">
        <div class="col-md-4">
            <div class="card">
                <div class="card-body text-center">
                    <span class="avatar avatar-xl mb-3" style="font-size:2rem">{{ strtoupper(substr($vendor->business_name,0,2)) }}</span>
                    <h3 class="mb-1">{{ $vendor->business_name }}</h3>
                    <p class="text-muted mb-1">{{ $vendor->user?->name }}</p>
                    <p class="text-muted mb-1">{{ $vendor->business_email ?? $vendor->user?->email }}</p>
                    <p class="text-muted mb-3">{{ $vendor->business_phone ?? '—' }}</p>
                    @php $sc=['pending'=>'warning','active'=>'success','suspended'=>'danger','rejected'=>'secondary']; @endphp
                    <span class="badge bg-{{ $sc[$vendor->status]??'secondary' }}-lt fs-6 text-capitalize me-1">{{ $vendor->status }}</span>
                    @php $kc=['pending'=>'warning','approved'=>'success','rejected'=>'danger']; @endphp
                    <span class="badge bg-{{ $kc[$vendor->kyc_status]??'secondary' }}-lt fs-6 text-capitalize">KYC: {{ $vendor->kyc_status }}</span>
                </div>
                <div class="card-footer">
                    <div class="row text-center">
                        <div class="col"><div class="fw-bold">{{ $vendor->orders->count() }}</div><div class="text-muted small">Orders</div></div>
                        <div class="col"><div class="fw-bold">{{ $vendor->rating }}</div><div class="text-muted small">Rating</div></div>
                        <div class="col"><div class="fw-bold">{{ $vendor->commission_rate }}%</div><div class="text-muted small">Commission</div></div>
                    </div>
                </div>
            </div>

            <div class="card mt-3">
                <div class="card-header"><h4 class="card-title">Vendor Type</h4></div>
                <div class="card-body">
                    <div class="d-flex align-items-center gap-2">
                        <span class="badge bg-blue-lt fs-5">{{ $vendor->vendorType?->name ?? 'None' }}</span>
                    </div>
                    <p class="text-muted small mt-2">Slug: {{ $vendor->vendorType?->slug }}</p>
                </div>
            </div>

            @if($vendor->vendorType?->slug === 'service_provider')
            <div class="card mt-3">
                <div class="card-header"><h4 class="card-title">Assigned Services</h4></div>
                <div class="card-body">
                    <form action="{{ route('admin.vendors.assign-services', $vendor) }}" method="POST">
                        @csrf
                        <div class="mb-3">
                            @forelse($availableServices as $service)
                            <label class="form-check">
                                <input class="form-check-input" type="checkbox" name="service_ids[]" value="{{ $service->id }}" 
                                    @checked(in_array($service->id, $assignedServiceIds))>
                                <span class="form-check-label">{{ $service->name }} (₹{{ number_format($service->fixed_price, 2) }})</span>
                            </label>
                            @empty
                            <p class="text-muted small">No services available for this vendor type.</p>
                            @endforelse
                        </div>
                        <button type="submit" class="btn btn-sm btn-primary w-100">Update Services</button>
                    </form>
                </div>
            </div>
            @endif

            <div class="card mt-3">
                <div class="card-header"><h4 class="card-title">Wallet</h4></div>
                <div class="card-body">
                    <div class="d-flex justify-content-between mb-2"><span class="text-muted">Balance</span><strong>₹{{ number_format($vendor->wallet?->balance ?? 0, 2) }}</strong></div>
                    <div class="d-flex justify-content-between"><span class="text-muted">Pending Withdrawal</span><strong>₹{{ number_format($vendor->wallet?->pending_withdrawal ?? 0, 2) }}</strong></div>
                </div>
            </div>

            @if($vendor->activeSubscription)
            <div class="card mt-3">
                <div class="card-header"><h4 class="card-title">Active Subscription</h4></div>
                <div class="card-body">
                    <div class="fw-bold">{{ $vendor->activeSubscription->plan?->name }}</div>
                    <div class="text-muted small">Expires: {{ $vendor->activeSubscription->expires_at?->format('d M Y') ?? '—' }}</div>
                </div>
            </div>
            @endif
        </div>

        <div class="col-md-8">
            <div class="card mb-4">
                <div class="card-header d-flex align-items-center justify-content-between">
                    <h4 class="card-title mb-0">KYC Documents</h4>
                    @if($vendor->kycDocuments->isNotEmpty())
                    <div class="d-flex gap-2">
                        <form action="{{ route('admin.kyc.approve-all', $vendor) }}" method="POST">@csrf<button class="btn btn-sm btn-success">Approve All</button></form>
                        <button class="btn btn-sm btn-danger" data-bs-toggle="modal" data-bs-target="#rejectKycModal">Reject All</button>
                    </div>
                    @endif
                    @if($vendor->kyc_status !== 'approved')
                    <div class="ms-auto d-flex gap-2">
                        <button class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#manualKycModal">Manual KYC</button>
                    </div>
                    @endif
                </div>
                <div class="list-group list-group-flush">
                    @forelse($vendor->kycDocuments as $doc)
                    <div class="list-group-item">
                        <div class="row align-items-center">
                            <div class="col">
                                <div class="fw-medium text-capitalize">{{ str_replace('_',' ',$doc->document_type) }}</div>
                                @if($doc->admin_remarks)<div class="text-muted small fst-italic">Remarks: {{ $doc->admin_remarks }}</div>@endif
                            </div>
                            <div class="col-auto d-flex align-items-center gap-2">
                                @php $kc=['pending'=>'warning','approved'=>'success','rejected'=>'danger']; @endphp
                                <span class="badge bg-{{ $kc[$doc->status]??'secondary' }}-lt text-capitalize">{{ $doc->status }}</span>
                                <a href="{{ $doc->file_url }}" target="_blank" class="btn btn-sm btn-outline-secondary">View</a>
                                @if($doc->status === 'pending')
                                <form action="{{ route('admin.kyc.document.approve', $doc) }}" method="POST">@csrf<button class="btn btn-sm btn-success">✓</button></form>
                                <button class="btn btn-sm btn-danger" data-bs-toggle="modal" data-bs-target="#rejectDoc{{ $doc->id }}">✗</button>
                                @endif
                            </div>
                        </div>
                    </div>
                    <div class="modal modal-blur fade" id="rejectDoc{{ $doc->id }}" tabindex="-1">
                        <div class="modal-dialog modal-sm modal-dialog-centered"><div class="modal-content">
                            <form action="{{ route('admin.kyc.document.reject', $doc) }}" method="POST">
                                @csrf
                                <div class="modal-header"><h5 class="modal-title">Reject Document</h5></div>
                                <div class="modal-body"><textarea name="remarks" class="form-control" rows="3" placeholder="Reason..." required></textarea></div>
                                <div class="modal-footer">
                                    <button type="button" class="btn btn-outline-secondary btn-sm" data-bs-dismiss="modal">Cancel</button>
                                    <button type="submit" class="btn btn-danger btn-sm">Reject</button>
                                </div>
                            </form>
                        </div></div>
                    </div>
                    @empty
                    <div class="list-group-item text-muted text-center">No KYC documents uploaded</div>
                    @endforelse
                </div>
            </div>

            <div class="card">
                <div class="card-header"><h4 class="card-title">Recent Orders</h4></div>
                <div class="table-responsive">
                    <table class="table table-vcenter card-table">
                        <thead><tr><th>Order #</th><th>Customer</th><th>Type</th><th>Total</th><th>Status</th><th>Date</th></tr></thead>
                        <tbody>
                            @forelse($vendor->orders as $order)
                            <tr>
                                <td><a href="{{ route('admin.orders.show', $order) }}">{{ $order->order_number }}</a></td>
                                <td>{{ $order->user?->name ?? '—' }}</td>
                                <td><span class="badge bg-blue-lt text-capitalize">{{ $order->type }}</span></td>
                                <td>₹{{ number_format($order->total, 2) }}</td>
                                <td>
                                    @php $c=['pending'=>'warning','completed'=>'success','cancelled'=>'danger','disputed'=>'red','in_progress'=>'primary','accepted'=>'info']; @endphp
                                    <span class="badge bg-{{ $c[$order->status]??'secondary' }}-lt text-capitalize">{{ str_replace('_',' ',$order->status) }}</span>
                                </td>
                                <td>{{ $order->created_at->format('d M Y') }}</td>
                            </tr>
                            @empty
                            <tr><td colspan="6" class="text-center text-muted">No orders yet</td></tr>
                            @endforelse
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Modals -->
<div class="modal modal-blur fade" id="suspendModal" tabindex="-1"><div class="modal-dialog modal-sm modal-dialog-centered"><div class="modal-content">
    <form action="{{ route('admin.vendors.suspend', $vendor) }}" method="POST">@csrf
        <div class="modal-header"><h5 class="modal-title">Suspend Vendor</h5></div>
        <div class="modal-body"><textarea name="reason" class="form-control" rows="3" placeholder="Reason (optional)..."></textarea></div>
        <div class="modal-footer"><button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button><button type="submit" class="btn btn-warning">Suspend</button></div>
    </form>
</div></div></div>

<div class="modal modal-blur fade" id="rejectModal" tabindex="-1"><div class="modal-dialog modal-sm modal-dialog-centered"><div class="modal-content">
    <form action="{{ route('admin.vendors.reject', $vendor) }}" method="POST">@csrf
        <div class="modal-header"><h5 class="modal-title">Reject Vendor</h5></div>
        <div class="modal-body"><textarea name="reason" class="form-control" rows="3" placeholder="Reason for rejection..." required></textarea></div>
        <div class="modal-footer"><button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button><button type="submit" class="btn btn-danger">Reject</button></div>
    </form>
</div></div></div>

<div class="modal modal-blur fade" id="rejectKycModal" tabindex="-1"><div class="modal-dialog modal-sm modal-dialog-centered"><div class="modal-content">
    <form action="{{ route('admin.kyc.reject-all', $vendor) }}" method="POST">@csrf
        <div class="modal-header"><h5 class="modal-title">Reject All KYC</h5></div>
        <div class="modal-body"><textarea name="remarks" class="form-control" rows="3" placeholder="Reason..." required></textarea></div>
        <div class="modal-footer"><button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button><button type="submit" class="btn btn-danger">Reject All</button></div>
    </form>
</div></div></div>

<div class="modal modal-blur fade" id="manualKycModal" tabindex="-1"><div class="modal-dialog modal-lg modal-dialog-centered"><div class="modal-content">
    <form action="{{ route('admin.vendors.manual-kyc', $vendor) }}" method="POST" enctype="multipart/form-data">@csrf
        <div class="modal-header"><h5 class="modal-title">Offline KYC Verification</h5></div>
        <div class="modal-body">
            <p class="text-muted small">Upload offline documents directly on behalf of the vendor to force approve their KYC.</p>
            
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label class="form-label required">ID Proof Document (PDF/JPG)</label>
                    <input type="file" name="id_proof" class="form-control" accept=".pdf,image/*" required onchange="previewImage(this, 'preview_id_proof')">
                    <img id="preview_id_proof" class="img-fluid mt-2 rounded d-none" style="max-height: 150px; object-fit: contain;">
                </div>
                <div class="col-md-6 mb-3">
                    <label class="form-label">ID Proof Number</label>
                    <input type="text" name="id_proof_number" class="form-control">
                </div>
            </div>

            <div class="row">
                <div class="col-md-6 mb-3">
                    <label class="form-label required">Address Proof Document (PDF/JPG)</label>
                    <input type="file" name="address_proof" class="form-control" accept=".pdf,image/*" required onchange="previewImage(this, 'preview_address_proof')">
                    <img id="preview_address_proof" class="img-fluid mt-2 rounded d-none" style="max-height: 150px; object-fit: contain;">
                </div>
                <div class="col-md-6 mb-3">
                    <label class="form-label required">Selfie / Photo (JPG/PNG)</label>
                    <input type="file" name="selfie" class="form-control" accept="image/*" required onchange="previewImage(this, 'preview_selfie')">
                    <img id="preview_selfie" class="img-fluid mt-2 rounded d-none" style="max-height: 150px; object-fit: contain;">
                </div>
            </div>

            <h4 class="mt-2 mb-3">Bank Details</h4>
            <div class="row">
                <div class="col-md-4 mb-3">
                    <label class="form-label required">Account Number</label>
                    <input type="text" name="account_number" class="form-control" required>
                </div>
                <div class="col-md-4 mb-3">
                    <label class="form-label required">IFSC/Routing Code</label>
                    <input type="text" name="ifsc" class="form-control" required>
                </div>
                <div class="col-md-4 mb-3">
                    <label class="form-label">UPI ID (Optional)</label>
                    <input type="text" name="upi_id" class="form-control">
                </div>
            </div>

            <div class="mb-3">
                <label class="form-label">Admin Remarks</label>
                <textarea name="remarks" class="form-control" rows="2" placeholder="e.g. Verified physical documents offline"></textarea>
            </div>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
            <button type="submit" class="btn btn-primary">Upload & Approve KYC</button>
        </div>
    </form>
</div></div></div>
@endsection

@push('scripts')
<script>
function previewImage(input, previewId) {
    const preview = document.getElementById(previewId);
    if (input.files && input.files[0]) {
        const file = input.files[0];
        
        // Only preview if it is an image
        if (file.type.match('image.*')) {
            const reader = new FileReader();
            reader.onload = function(e) {
                preview.src = e.target.result;
                preview.classList.remove('d-none');
            }
            reader.readAsDataURL(file);
        } else {
            // Hide preview if not an image (e.g. PDF)
            preview.src = '';
            preview.classList.add('d-none');
        }
    } else {
        preview.src = '';
        preview.classList.add('d-none');
    }
}
</script>
@endpush
