<?php
use yii\helpers\Url;
/** @var $clients      array */
/** @var $auctions     array */
/** @var $warehouses   array */
/** @var $destinations array */
?>

<?php
$this->registerCssFile('https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css');
$this->registerCssFile('https://cdn.jsdelivr.net/npm/choices.js/public/assets/styles/choices.min.css');

$this->registerJsFile(
    'https://cdn.jsdelivr.net/npm/flatpickr',
    ['position' => \yii\web\View::POS_END]
);
$this->registerJsFile(
    'https://cdn.jsdelivr.net/npm/choices.js/public/assets/scripts/choices.min.js',
    ['position' => \yii\web\View::POS_END]
);

$this->registerCss(<<<CSS
.choices__inner {
    border-radius: 8px !important;
    border: 1px solid #dee2e6 !important;
    background-color: #fff !important;
    min-height: 42px !important;
    padding-top: 6px !important;
}
.choices__list--dropdown {
    border-radius: 12px !important;
    box-shadow: 0 8px 24px rgba(0,0,0,0.12) !important;
    border: 1px solid #e9ecef !important;
}
.choices__list--dropdown .choices__item--selectable.is-highlighted {
    background-color: #e8f0fe !important;
    color: #1a73e8 !important;
}
#carModalTab .nav-link {
    color: #6c757d;
    border: none;
    border-bottom: 3px solid transparent;
    transition: all 0.2s;
}
#carModalTab .nav-link.active,
#carModalTab .nav-link:hover {
    background: transparent !important;
    border-bottom: 3px solid #0d6efd !important;
    color: #0d6efd !important;
}
.upload-dropzone {
    cursor: pointer;
    transition: all 0.25s ease;
    border-color: #ced4da !important;
}
.upload-dropzone:hover,
.upload-dropzone.drag-over {
    border-color: #0d6efd !important;
    background-color: #f0f7ff !important;
    transform: scale(1.005);
}
.object-fit-cover { object-fit: cover; }
.flatpickr-input { background-color: #fff !important; }
.form-control.is-invalid,
.form-select.is-invalid {
    border-color: #dc3545 !important;
    box-shadow: 0 0 0 0.2rem rgba(220,53,69,.15) !important;
}
.invalid-feedback {
    display: none;
    font-size: 0.775rem;
    color: #dc3545;
    margin-top: 4px;
}
.form-control.is-invalid ~ .invalid-feedback,
.form-select.is-invalid ~ .invalid-feedback {
    display: block;
}
.required-star {
    color: #dc3545;
    font-weight: bold;
    margin-left: 2px;
}
CSS);
?>

<div class="modal fade" id="carModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-xl modal-dialog-centered">
        <div class="modal-content border-0 shadow-lg rounded-4">

            <!-- Header -->
            <div class="modal-header border-0 bg-light rounded-top-4 px-4">
                <h5 class="fw-bold mb-0">
                    <i class="bi bi-car-front-fill me-2 text-primary"></i>
                    <span v-if="isEditing">Update Vehicle: <strong>{{ formData.vin || 'N/A' }}</strong></span>
                    <span v-else>Register New Vehicle</span>
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>

            <div class="modal-body p-0">

                <!-- Tabs -->
                <ul class="nav nav-tabs nav-fill bg-light px-3" id="carModalTab" role="tablist">
                    <li class="nav-item" role="presentation">
                        <button class="nav-link active fw-semibold py-3"
                                id="tab-basic-btn"
                                data-bs-toggle="tab"
                                data-bs-target="#tab-basic"
                                type="button" role="tab"
                                aria-controls="tab-basic"
                                aria-selected="true">
                            <i class="bi bi-card-checklist me-1"></i> Vehicle & Logistics
                        </button>
                    </li>
                    <li class="nav-item" role="presentation"
                        v-for="stage in photoStages" :key="stage.id">
                        <button class="nav-link fw-semibold py-3 position-relative"
                                data-bs-toggle="tab"
                                :id="'tab-' + stage.id + '-btn'"
                                :data-bs-target="'#tab-' + stage.id"
                                :aria-controls="'tab-' + stage.id"
                                type="button" role="tab">
                            <i :class="'bi ' + stage.icon + ' me-1'"></i>
                            {{ stage.label }} Photos
                            <span v-if="getPhotoCount(stage.id) > 0"
                                  class="badge bg-primary rounded-pill ms-1"
                                  style="font-size:0.65rem;">
                                {{ getPhotoCount(stage.id) }}
                            </span>
                        </button>
                    </li>
                </ul>

                <!-- Form -->
                <form id="carForm" @submit.prevent="saveCar" novalidate>
                    <div class="tab-content p-4" id="carModalTabContent">

                        <!-- ===== TAB 1: Vehicle & Logistics ===== -->
                        <div class="tab-pane fade show active" id="tab-basic" role="tabpanel"
                             aria-labelledby="tab-basic-btn">
                            <div class="row g-3">

                                <!-- Row 1: Year | VIN | Lot | Title -->
                                <div class="col-md-2">
                                    <label for="field_year" class="form-label small fw-bold text-muted">
                                        YEAR <span class="required-star">*</span>
                                    </label>
                                    <input type="text"
                                           id="field_year"
                                           name="Car[year]"
                                           v-model="formData.year"
                                           :class="['form-control shadow-sm', formErrors.year ? 'is-invalid' : '']"
                                           placeholder="e.g. 2020"
                                           @blur="validateField('year')">
                                    <div class="invalid-feedback">Year is required.</div>
                                </div>

                                <div class="col-md-4">
                                    <label for="field_vin" class="form-label small fw-bold text-muted">
                                        VIN <span class="text-muted fw-normal">(Optional)</span>
                                    </label>
                                    <input type="text"
                                           id="field_vin"
                                           name="Car[vin]"
                                           v-model="formData.vin"
                                           class="form-control shadow-sm"
                                           placeholder="Vehicle Identification Number">
                                </div>

                                <div class="col-md-3">
                                    <label for="field_lot" class="form-label small fw-bold text-muted">
                                        LOT <span class="required-star">*</span>
                                    </label>
                                    <input type="text"
                                           id="field_lot"
                                           name="Car[lot]"
                                           v-model="formData.lot"
                                           :class="['form-control shadow-sm', formErrors.lot ? 'is-invalid' : '']"
                                           placeholder="Lot number"
                                           @blur="validateField('lot')">
                                    <div class="invalid-feedback">Lot number is required.</div>
                                </div>

                                <div class="col-md-3">
                                    <label for="field_title" class="form-label small fw-bold text-muted">
                                        TITLE / KEY <span class="required-star">*</span>
                                    </label>
                                    <input type="text"
                                           id="field_title"
                                           name="Car[title]"
                                           v-model="formData.title"
                                           :class="['form-control shadow-sm', formErrors.title ? 'is-invalid' : '']"
                                           placeholder="Title status"
                                           @blur="validateField('title')">
                                    <div class="invalid-feedback">Title / Key is required.</div>
                                </div>

                                <!-- Row 2: Info | Liner -->
                                <div class="col-md-8">
                                    <label for="field_info" class="form-label small fw-bold text-muted">
                                        VEHICLE INFO <span class="required-star">*</span>
                                    </label>
                                    <input type="text"
                                           id="field_info"
                                           name="Car[info]"
                                           v-model="formData.info"
                                           :class="['form-control shadow-sm', formErrors.info ? 'is-invalid' : '']"
                                           placeholder="Color, Engine, Specs..."
                                           @blur="validateField('info')">
                                    <div class="invalid-feedback">Vehicle info is required.</div>
                                </div>

                                <div class="col-md-4">
                                    <label for="field_liner" class="form-label small fw-bold text-muted">
                                        LINER <span class="required-star">*</span>
                                    </label>
                                    <select id="field_liner"
                                            name="Car[liner]"
                                            v-model="formData.liner"
                                            :class="['form-select shadow-sm', formErrors.liner ? 'is-invalid' : '']"
                                            @change="validateField('liner')">
                                        <option value="">Select Liner...</option>
                                        <option v-for="l in liners" :key="l" :value="l">{{ l }}</option>
                                    </select>
                                    <div class="invalid-feedback">Please select a liner.</div>
                                </div>

                                <!-- Row 3: Dates (all optional) -->
                                <div class="col-md-4">
                                    <label for="purchaseDateInput" class="form-label small fw-bold text-muted">
                                        PURCHASE DATE <span class="text-muted fw-normal">(Optional)</span>
                                    </label>
                                    <div class="input-group shadow-sm">
                                        <span class="input-group-text bg-white border-end-0">
                                            <i class="bi bi-calendar-event text-primary"></i>
                                        </span>
                                        <input type="text"
                                               id="purchaseDateInput"
                                               name="Car[purchase_date]"
                                               class="form-control border-start-0 bg-white"
                                               placeholder="DD/MM/YYYY"
                                               autocomplete="off"
                                               readonly>
                                    </div>
                                </div>

                                <div class="col-md-4">
                                    <label for="receivedDateInput" class="form-label small fw-bold text-muted">
                                        RECEIVED DATE <span class="text-muted fw-normal">(Optional)</span>
                                    </label>
                                    <div class="input-group shadow-sm">
                                        <span class="input-group-text bg-white border-end-0">
                                            <i class="bi bi-calendar-check text-success"></i>
                                        </span>
                                        <input type="text"
                                               id="receivedDateInput"
                                               name="Car[received_date]"
                                               class="form-control border-start-0 bg-white"
                                               placeholder="DD/MM/YYYY"
                                               autocomplete="off"
                                               readonly>
                                    </div>
                                </div>

                                <div class="col-md-4">
                                    <label for="etaDateInput" class="form-label small fw-bold text-muted">
                                        ETA DATE <span class="text-muted fw-normal">(Optional)</span>
                                    </label>
                                    <div class="input-group shadow-sm">
                                        <span class="input-group-text bg-white border-end-0">
                                            <i class="bi bi-truck text-warning"></i>
                                        </span>
                                        <input type="text"
                                               id="etaDateInput"
                                               name="Car[eta_date]"
                                               class="form-control border-start-0 bg-white"
                                               placeholder="DD/MM/YYYY"
                                               autocomplete="off"
                                               readonly>
                                    </div>
                                </div>

                                <!-- Row 4: Auction | Warehouse | Destination | Container -->
                                <div class="col-md-3">
                                    <label for="field_auction_id" class="form-label small fw-bold text-muted">
                                        AUCTION TYPE <span class="required-star">*</span>
                                    </label>
                                    <select id="field_auction_id"
                                            name="Car[auction_id]"
                                            v-model="formData.auction_id"
                                            :class="['form-select shadow-sm', formErrors.auction_id ? 'is-invalid' : '']"
                                            @change="validateField('auction_id')">
                                        <option value="">Select Auction...</option>
                                        <?php foreach ($auctions as $a): ?>
                                            <option value="<?= $a['id'] ?>">
                                                <?= htmlspecialchars($a['name']) ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                    <div class="invalid-feedback">Please select an auction type.</div>
                                </div>

                                <div class="col-md-3">
                                    <label for="field_warehouse_id" class="form-label small fw-bold text-muted">
                                        WAREHOUSE PORT <span class="required-star">*</span>
                                    </label>
                                    <select id="field_warehouse_id"
                                            name="Car[warehouse_id]"
                                            v-model="formData.warehouse_id"
                                            :class="['form-select shadow-sm', formErrors.warehouse_id ? 'is-invalid' : '']"
                                            @change="validateField('warehouse_id')">
                                        <option value="">Select Warehouse...</option>
                                        <?php foreach ($warehouses as $w): ?>
                                            <option value="<?= $w['id'] ?>">
                                                <?= htmlspecialchars($w['name']) ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                    <div class="invalid-feedback">Please select a warehouse.</div>
                                </div>

                                <div class="col-md-3">
                                    <label for="field_destination_id" class="form-label small fw-bold text-muted">
                                        DESTINATION <span class="required-star">*</span>
                                    </label>
                                    <select id="field_destination_id"
                                            name="Car[destination_id]"
                                            v-model="formData.destination_id"
                                            :class="['form-select shadow-sm', formErrors.destination_id ? 'is-invalid' : '']"
                                            @change="validateField('destination_id')">
                                        <option value="">Select Destination...</option>
                                        <?php foreach ($destinations as $d): ?>
                                            <option value="<?= $d['id'] ?>">
                                                <?= htmlspecialchars($d['name']) ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                    <div class="invalid-feedback">Please select a destination.</div>
                                </div>

                                <div class="col-md-3">
                                    <label for="field_container" class="form-label small fw-bold text-muted">
                                        CONTAINER NO <span class="required-star">*</span>
                                    </label>
                                    <input type="text"
                                           id="field_container"
                                           name="Car[container]"
                                           v-model="formData.container"
                                           :class="['form-control shadow-sm', formErrors.container ? 'is-invalid' : '']"
                                           placeholder="Container number"
                                           @blur="validateField('container')">
                                    <div class="invalid-feedback">Container number is required.</div>
                                </div>

                                <!-- Row 5: Shipping | Price | Status -->
                                <div class="col-md-4">
                                    <label for="field_shipping_line" class="form-label small fw-bold text-muted">
                                        SHIPPING LINE (URL) <span class="required-star">*</span>
                                    </label>
                                    <input type="text"
                                           id="field_shipping_line"
                                           name="Car[shipping_line]"
                                           v-model="formData.shipping_line"
                                           :class="['form-control shadow-sm', formErrors.shipping_line ? 'is-invalid' : '']"
                                           placeholder="https://..."
                                           @blur="validateField('shipping_line')">
                                    <div class="invalid-feedback">Shipping line is required.</div>
                                </div>

                                <div class="col-md-4">
                                    <label for="field_price" class="form-label small fw-bold text-muted">
                                        PRICE ($) <span class="required-star">*</span>
                                    </label>
                                    <div class="input-group shadow-sm">
                                        <span class="input-group-text">$</span>
                                        <input type="number"
                                               id="field_price"
                                               name="Car[price]"
                                               step="0.01"
                                               min="0"
                                               v-model="formData.price"
                                               :class="['form-control', formErrors.price ? 'is-invalid' : '']"
                                               @blur="validateField('price')">
                                        <div class="invalid-feedback">Price is required.</div>
                                    </div>
                                </div>

                                <div class="col-md-4">
                                    <label for="field_status" class="form-label small fw-bold text-muted">
                                        STATUS <span class="required-star">*</span>
                                    </label>
                                    <select id="field_status"
                                            name="Car[status]"
                                            v-model="formData.status"
                                            :class="['form-select shadow-sm', formErrors.status ? 'is-invalid' : '']"
                                            @change="validateField('status')">
                                        <option value="">Select Status...</option>
                                        <option value="at_auction">At Auction</option>
                                        <option value="at_yard">At Yard</option>
                                        <option value="arrived">Arrived</option>
                                        <option value="paid">Paid</option>
                                        <option value="unpaid">Unpaid</option>
                                    </select>
                                    <div class="invalid-feedback">Please select a status.</div>
                                </div>

                                <!-- Row 6: Client -->
                                <div class="col-md-12">
                                    <label for="clientSelectEl" class="form-label small fw-bold text-muted">
                                        CLIENT <span class="required-star">*</span>
                                    </label>
                                    <select id="clientSelectEl" name="Car[client_id]"></select>
                                    <div v-if="formErrors.client_id"
                                         class="text-danger small mt-1">
                                        <i class="bi bi-exclamation-circle me-1"></i>
                                        Please select a client.
                                    </div>
                                    <div v-if="formData.client_id" class="mt-2 small">
                                        <i class="bi bi-person-fill text-primary me-1"></i>
                                        <strong>{{ getClientName(formData.client_id) }}</strong>
                                        <span class="ms-2 text-muted">
                                            <i class="bi bi-telephone me-1"></i>
                                            {{ getClientPhone(formData.client_id) }}
                                        </span>
                                    </div>
                                </div>

                                <!-- Row 7: Note -->
                                <div class="col-md-12">
                                    <label for="field_note" class="form-label small fw-bold text-danger">
                                        <i class="bi bi-exclamation-triangle me-1"></i>
                                        INTERNAL NOTE <span class="required-star">*</span>
                                        <span class="text-muted fw-normal ms-1">(enter "-" if none)</span>
                                    </label>
                                    <textarea id="field_note"
                                              name="Car[note]"
                                              v-model="formData.note"
                                              :class="['form-control shadow-sm text-danger fw-semibold', formErrors.note ? 'is-invalid' : '']"
                                              rows="2"
                                              placeholder="Internal notes (visible in red)..."
                                              @blur="validateField('note')"></textarea>
                                    <div class="invalid-feedback">Note is required. Enter "-" if none.</div>
                                </div>

                            </div>
                        </div><!-- end tab-basic -->

                        <!-- ===== TABS 2,3,4: Photo Tabs ===== -->
                        <div v-for="stage in photoStages"
                             :key="stage.id"
                             class="tab-pane fade"
                             :id="'tab-' + stage.id"
                             :aria-labelledby="'tab-' + stage.id + '-btn'"
                             role="tabpanel">

                            <!-- Dropzone -->
                            <div class="upload-dropzone text-center border border-2 border-dashed rounded-4 p-4 mb-4"
                                 @click="triggerFileInput(stage.id)"
                                 @dragover.prevent="onDragOver($event)"
                                 @dragleave="onDragLeave($event)"
                                 @drop.prevent="onDrop($event, stage.id)">
                                <i class="bi bi-cloud-arrow-up-fill fs-1 text-primary"></i>
                                <h6 class="mt-2 fw-bold">Click or Drag & Drop</h6>
                                <p class="text-muted small mb-0">
                                    Upload {{ stage.label }} photos — JPG, PNG, WEBP (max 5MB each)
                                </p>
                                <input
                                    :ref="'fileInput_' + stage.id"
                                    :id="'fileInput_' + stage.id"
                                    :name="'image_files[' + stage.id + '][]'"
                                    :aria-label="stage.label + ' photo upload'"
                                    type="file"
                                    class="d-none"
                                    multiple
                                    accept="image/jpeg,image/png,image/webp,image/gif"
                                    @change="handleFileSelect($event, stage.id)">
                            </div>

                            <!-- Empty state -->
                            <div v-if="getPhotoCount(stage.id) === 0"
                                 class="text-center text-muted py-4">
                                <i class="bi bi-image fs-2 d-block mb-2"></i>
                                No photos yet for this section.
                            </div>

                            <!-- Photo Grid -->
                            <div v-else class="row g-2">

                                <!-- Existing saved images -->
                                <div v-for="img in getExistingImages(stage.id)"
                                     :key="'exist-' + img.id"
                                     class="col-6 col-md-3 col-lg-2 position-relative">
                                    <div class="card h-100 border-0 shadow-sm rounded-3 overflow-hidden">
                                        <img :src="uploadBaseUrl + img.image_path"
                                             :alt="stage.label + ' saved image'"
                                             class="card-img-top object-fit-cover"
                                             height="110"
                                             @error="onImgError($event)">
                                        <div class="card-body p-1 text-center">
                                            <span class="badge bg-success-subtle text-success"
                                                  style="font-size:0.6rem;">
                                                <i class="bi bi-check-circle me-1"></i>Saved
                                            </span>
                                        </div>
                                        <button type="button"
                                                :aria-label="'Delete ' + stage.label + ' image'"
                                                @click="deleteExistingImage(img.id)"
                                                class="btn btn-danger btn-sm position-absolute top-0 end-0 m-1 rounded-circle p-0"
                                                style="width:22px;height:22px;line-height:1;">
                                            <i class="bi bi-x" style="font-size:0.75rem;"></i>
                                        </button>
                                    </div>
                                </div>

                                <!-- ✅ FIX #4: Pending previews — fixed broken style attribute -->
                                <div v-for="(preview, index) in newPreviews[stage.id]"
                                     :key="'new-' + index"
                                     class="col-6 col-md-3 col-lg-2 position-relative">
                                    <div class="card h-100 border-0 shadow-sm rounded-3 overflow-hidden border-primary">
                                        <img :src="preview"
                                             :alt="stage.label + ' pending image ' + (index + 1)"
                                             class="card-img-top object-fit-cover"
                                             height="110">
                                        <div class="card-body p-1 text-center">
                                            <span class="badge bg-warning-subtle text-warning"
                                                  style="font-size:0.6rem;">
                                                <i class="bi bi-clock me-1"></i>Pending
                                            </span>
                                        </div>
                                        <button type="button"
                                                :aria-label="'Remove pending image ' + (index + 1)"
                                                @click="removeNewImage(stage.id, index)"
                                                class="btn btn-dark btn-sm position-absolute top-0 end-0 m-1 rounded-circle p-0"
                                                style="width:22px;height:22px;line-height:1;">
                                            <i class="bi bi-x" style="font-size:0.75rem;"></i>
                                        </button>
                                    </div>
                                </div>

                            </div>
                        </div><!-- end photo tab-pane -->

                    </div><!-- end tab-content -->

                    <!-- Modal Footer -->
                    <div class="d-flex justify-content-between align-items-center px-4 pb-4 pt-3 border-top mt-2">
                        <div class="small text-muted">
                            <i class="bi bi-info-circle me-1"></i>
                            Fields marked <span class="text-danger fw-bold">*</span> are required.
                        </div>
                        <div class="d-flex gap-2">
                            <button type="button"
                                    class="btn btn-light rounded-pill px-4 fw-semibold"
                                    data-bs-dismiss="modal">
                                <i class="bi bi-x-lg me-1"></i> Cancel
                            </button>
                            <button type="submit"
                                    class="btn btn-primary rounded-pill px-4 shadow-sm fw-semibold"
                                    :disabled="loading">
                                <span v-if="loading"
                                      class="spinner-border spinner-border-sm me-1"
                                      role="status"
                                      aria-label="Saving..."></span>
                                <i v-else class="bi bi-check-lg me-1"></i>
                                {{ isEditing ? 'Update Vehicle' : 'Create Vehicle' }}
                            </button>
                        </div>
                    </div>

                </form>
            </div><!-- end modal-body -->
        </div><!-- end modal-content -->
    </div><!-- end modal-dialog -->
</div><!-- end #carModal -->