@extends('layouts.app')

@section('content')
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css" rel="stylesheet">

    <div class="container">
        {{-- Flash Messages --}}
        @if (session('success'))
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                {{ session('success') }}
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        @endif

        @if (session('error'))
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                {{ session('error') }}
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        @endif

        @if ($errors->any())
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <ul class="mb-0">
                    @foreach ($errors->all() as $error)
                        <li>{{ $error }}</li>
                    @endforeach
                </ul>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        @endif

        <div class="text-center mb-1">
            <h1 class="display-8 fw-bold text-uppercase text-danger" style="letter-spacing: 2px;">
                Khan Motor's 
            </h1>
            <!-- <hr class="w-25 mx-auto border-5 border-danger"> -->
        </div>

        <h2 class="text-center mb-4">Car Sales</h2>
        <div class="mb-3 d-flex justify-content-end">
        <div class="input-group" style="width: 30%;">
            <span class="input-group-text bg-white">
                <i class="bi bi-search"></i>
            </span>
            <input type="text" id="tableSearch" class="form-control" placeholder="Search in table...">
        </div>
    </div>
        <table class="table table-bordered table-striped">
            <thead>
                <tr style="text-align: center;">
                    <th>Car ID</th>
                    <th>Recipt No</th>
                    <th>Registration No</th>
                    <th>Make</th>
                    <th>Varient</th>
                    <th>Color</th>
                    <th>Model</th>
                    <th>Seller Name</th>
                    <th>Buyer Name</th>
                    <th>Sold Price</th>
                    <th>Remaining</th>
                    <th>Date</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>
                @foreach($carSales as $sale)
                    <tr style="text-align: center;">
                        <td>{{ $loop->iteration }}</td>
                        <td>KM-{{ \Carbon\Carbon::parse($sale->date)->format('Y') }}-{{ $sale->id }}</td>
                        <td>{{ $sale->registration_no }}</td>
                        <td>{{ $sale->make }}</td>
                        <td>{{ $sale->varient }}</td>
                        <td>{{ $sale->color }}</td>
                        <td>{{ $sale->model }}</td>
                        <td>{{ $sale->seller_name }} <small hidden>{{ $sale->seller_cnic }}</small>  </td>
                        <td>{{ $sale->buyer_name }} <small hidden>{{ $sale->buyer_cnic }}</small>  </td>
                        <td>{{ number_format($sale->soled_price) }}</td>
                        
                        <td>{{ number_format( $sale->soled_price - ($sale->payments->sum('amount') + $sale->received_amount)) }}</td>

                        <td>{{ \Carbon\Carbon::parse($sale->date)->format('d/m/Y') }}</td>
                        <td class="action-buttons">
                            <a target="blank" href="{{ route('car.sales.show', $sale->id) }}" class="btn btn-info btn-sm"><i class="bi bi-eye"></i></a>
                            <a target="blank" href="{{ route('car.sales.print', $sale->id) }}" class="btn btn-success btn-sm"><i class="bi bi-printer"></i></a>
                            <a target="blank" href="{{ route('car.sales.print2', $sale->id) }}" class="btn btn-warning btn-sm"><i class="bi bi-printer"></i></a>

                            <a href="{{ route('edit.sale.info', $sale->id) }}" class="btn btn-primary  btn-sm"><i class="bi bi-pencil"></i></a>
                            

                            <!-- Receive Payment Button -->
                            <!-- Add Payment Button -->
                            <button class="btn btn-warning btn-sm" data-bs-toggle="modal" data-bs-target="#paymentModal{{ $sale->id }}">
                                <i class="bi bi-cash-stack"></i>
                            </button>

                            <!-- Commission Button -->
                            @if(!$sale->commission) 
                                <button class="btn btn-dark btn-sm" data-bs-toggle="modal" data-bs-target="#commissionModal{{ $sale->id }}">
                                    <i class="bi bi-percent"></i>
                                </button>
                            @endif

                            @if(auth()->user()->is_admin == 0)

                            @else
                            <form action="{{ route('car.sales.destroy', $sale->id) }}" method="POST" style="display:inline;">
                                @csrf
                                @method('DELETE')
                                <button type="submit" class="btn btn-danger btn-sm"
                                    onclick="return confirm('Are you sure you want to delete KM-{{ \Carbon\Carbon::parse($sale->date)->format('Y') }}-{{ $sale->id }} record?');">
                                    <i class="bi bi-trash"></i>
                                </button>
                            </form>
                            @endif                            


                        </td>
                    </tr>



<!-- Payment Modal -->
<div class="modal fade" id="paymentModal{{ $sale->id }}" tabindex="-1" aria-labelledby="paymentModalLabel{{ $sale->id }}" aria-hidden="true">
  <div class="modal-dialog">
    <form action="{{ route('car.sales.update.payment', $sale->id) }}" method="POST">
        @csrf
        @method('PATCH')
        <div class="modal-content">
        <div class="modal-header d-flex flex-column align-items-center">
            <h5 class="modal-title text-center" id="paymentModalLabel{{ $sale->id }}">
                Add Payment for <br>
                <big>{{ $sale->buyer_name }} {{ $sale->registration_no }}</big>
            </h5>
            <button type="button" class="btn-close position-absolute end-0 me-3" 
                    data-bs-dismiss="modal" aria-label="Close"></button>
        </div>

          <div class="modal-body">
              <div class="mb-3">              
                <center>
                    <p class="text"> Remaining: {{ number_format( $sale->soled_price - ($sale->payments->sum('amount') + $sale->received_amount)) }}</p>
                </center>
                  <label for="received_amount" class="form-label">New Payment Amount</label>
                  <input type="text" class="form-control"  name="additional_amount" id="additional_amount" required>

                <script>
                document.getElementById('additional_amount').addEventListener('input', function (e) {
                    let value = e.target.value.replace(/,/g, ''); // remove existing commas
                    if (!isNaN(value) && value !== '') {
                        e.target.value = Number(value).toLocaleString(); // format with commas
                    }
                });
                </script>

        <label for="date">Date of Payment</label>
                  <input type="date" name="date" id="date" class="form-control" required value="{{ date('Y-m-d') }}">
       </div>
              <!-- <p class="text-muted">Current Received: {{ $sale->received_amount }}</p> -->
              <p class="text-muted">Total Price: {{ $sale->soled_price }}</p>
          </div>
          <div class="modal-footer">
            <button type="submit" class="btn btn-success">Add Payment</button>
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
          </div>
        </div>
    </form>
  </div>
</div>








<!-- Commission Modal -->
<div class="modal fade" id="commissionModal{{ $sale->id }}" tabindex="-1" aria-labelledby="commissionModalLabel{{ $sale->id }}" aria-hidden="true">
  <div class="modal-dialog">
    <form action="{{ route('car.sales.store.commission', $sale->id) }}" method="POST">
        @csrf
        <div class="modal-content">
            <div class="modal-header d-flex flex-column align-items-center">
                <h5 class="modal-title text-center" id="commissionModalLabel{{ $sale->id }}">
                    Add Commission Details <br>
                    <big>   {{ $sale->registration_no }}</big>
                </h5>
                <button type="button" class="btn-close position-absolute end-0 me-3"
                        data-bs-dismiss="modal" aria-label="Close"></button>
            </div>

            <div class="modal-body">
                <div class="mb-3">
                    <label>Date</label>
                    <input type="date" name="date" class="form-control" value="{{ date('Y-m-d') }}" required>
                </div>
                <div class="mb-3">
                    <label>Buyer Commission</label>
                    <input type="number" name="buyer_commission" class="form-control" min="0" required>
                </div>
                <div class="mb-3">
                    <label>Seller Commission</label>
                    <input type="number" name="seller_commission" class="form-control" min="0" required>
                </div>
                <div class="mb-3">
                    <label>Receiver Name</label>
                    <input type="text" name="receiver_name" class="form-control" required>
                </div>

                <!-- Hidden Car Details -->
                <input type="hidden" name="registration_no" value="{{ $sale->registration_no }}">
                <input type="hidden" name="buyer_name" value="{{ $sale->buyer_name }}">
                <input type="hidden" name="seller_name" value="{{ $sale->seller_name }}">
                <input type="hidden" name="car_sale_id" value="{{ $sale->id }}">
            </div>

            <div class="modal-footer">
                <button type="submit" class="btn btn-success">Save Commission</button>
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
            </div>
        </div>
    </form>
  </div>
</div>


                @endforeach
            </tbody>
        </table>
    </div>
@endsection



<script>
// function printForm(carId) {
//     window.open(`/cars/${carId}/print`, '_blank');
// }

document.addEventListener('DOMContentLoaded', function () {
    const searchInput = document.getElementById('tableSearch');
    const tableRows = document.querySelectorAll('table tbody tr');

    searchInput.addEventListener('keyup', function () {
        const query = this.value.toLowerCase();

        tableRows.forEach(function (row) {
            const rowText = row.textContent.toLowerCase();
            row.style.display = rowText.includes(query) ? '' : 'none';
        });
    });
});
</script>



<style>
        .action-buttons  {
        white-space: wrap;
        line-height: 30px;
        }
    .drift-car {
        position: fixed;
        bottom: 220px;
        left: -200px;
        width: 500px;
        height: auto;
        z-index: 9999;
        animation: drift 4s ease-out forwards;
        pointer-events: none;
    }

    @keyframes drift {
        0% { left: -200px; transform: rotate(0deg) scale(1); opacity: 0.5; }
        50% { transform: rotate(0deg) scale(1.2); }
        100% { left: 120%; transform: rotate(0deg) scale(0.8); opacity: 1; }
    }
</style>

<script>
    function showDriftAnimation() {
        const carImage = document.createElement('img');
        carImage.src = '/drift2.png'; // <- **change this to your car drift image**
        carImage.classList.add('drift-car');
        document.body.appendChild(carImage);

        setTimeout(() => {
            carImage.remove();
        }, 3000); // remove after animation
    }
</script>



<!-- Payment Modal -->
<div class="modal fade" id="paymentModal{{ $sale->id }}" tabindex="-1" aria-labelledby="paymentModalLabel{{ $sale->id }}" aria-hidden="true">
  <div class="modal-dialog">
    <form action="{{ route('car.sales.update.payment', $sale->id) }}" method="POST">
        @csrf
        @method('PATCH')
        <div class="modal-content">
        <div class="modal-header d-flex flex-column align-items-center">
            <h5 class="modal-title text-center" id="paymentModalLabel{{ $sale->id }}">
                Add Payment for <br>
                <big>{{ $sale->buyer_name }} {{ $sale->registration_no }}</big>
            </h5>
            <button type="button" class="btn-close position-absolute end-0 me-3" 
                    data-bs-dismiss="modal" aria-label="Close"></button>
        </div>

          <div class="modal-body">
              <div class="mb-3">
                  <label for="received_amount" class="form-label">New Payment Amount</label>
                  <input type="number" class="form-control" name="additional_amount" min="1" required>
                  <label for="date">Date of Payment</label>
                  <input type="date" name="date" id="date" class="form-control" required value="{{ date('Y-m-d') }}">
       </div>
              <!-- <p class="text-muted">Current Received: {{ $sale->received_amount }}</p> -->
              <p class="text-muted">Total Price: {{ $sale->soled_price }}</p>
          </div>
          <div class="modal-footer">
            <button type="submit" class="btn btn-success">Add Payment</button>
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
          </div>
        </div>
    </form>
  </div>
</div>








<!-- Commission Modal -->
<div class="modal fade" id="commissionModal{{ $sale->id }}" tabindex="-1" aria-labelledby="commissionModalLabel{{ $sale->id }}" aria-hidden="true">
  <div class="modal-dialog">
    <form action="{{ route('car.sales.store.commission', $sale->id) }}" method="POST">
        @csrf
        <div class="modal-content">
            <div class="modal-header d-flex flex-column align-items-center">
                <h5 class="modal-title text-center" id="commissionModalLabel{{ $sale->id }}">
                    Add Commission Details <br>
                    <big>{{ $sale->buyer_name }} - {{ $sale->registration_no }}</big>
                </h5>
                <button type="button" class="btn-close position-absolute end-0 me-3"
                        data-bs-dismiss="modal" aria-label="Close"></button>
            </div>

            <div class="modal-body">
                <div class="mb-3">
                    <label>Date</label>
                    <input type="date" name="date" class="form-control" value="{{ date('Y-m-d') }}" required>
                </div>
                <div class="mb-3">
                    <label>Buyer Commission</label>
                    <input type="number" name="buyer_commission" class="form-control" min="0" required>
                </div>
                <div class="mb-3">
                    <label>Seller Commission</label>
                    <input type="number" name="seller_commission" class="form-control" min="0" required>
                </div>
                <div class="mb-3">
                    <label>Receiver Name</label>
                    <input type="text" name="receiver_name" class="form-control" required>
                </div>

                <!-- Hidden Car Details -->
                <input type="hidden" name="registration_no" value="{{ $sale->registration_no }}">
                <input type="hidden" name="buyer_name" value="{{ $sale->buyer_name }}">
                <input type="hidden" name="seller_name" value="{{ $sale->seller_name }}">
                <input type="hidden" name="car_sale_id" value="{{ $sale->id }}">
            </div>

            <div class="modal-footer">
                <button type="submit" class="btn btn-success">Save Commission</button>
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
            </div>
        </div>
    </form>
  </div>
</div>