@extends('layouts.app')

@section('title', 'Edit Car Inspection Report')

@section('content')
<style>
    /* Keep the same CSS styles as you provided */
    .form-container {
        background-color: #fff;
        padding: 30px;
        border-radius: 10px;
        box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        max-width: 800px;
        margin: 30px auto;
        font-family: Arial, sans-serif;
    }
    .form-container h2 {
        text-align: center;
        margin-bottom: 25px;
    }
    .form-group {
        display: flex;
        flex-wrap: wrap;
        margin-bottom: 15px;
    }
    .form-group label {
        flex: 0 0 40%;
        font-weight: bold;
        margin-bottom: 5px;
    }
    .form-group input,
    .form-group select,
    .form-group textarea {
        flex: 0 0 60%;
        padding: 10px;
        font-size: 14px;
        border-radius: 5px;
        border: 1px solid #ccc;
    }
    .comments-section, .sketch-section, .form-control {
        margin-top: 20px;
    }
    button[type="submit"] {
        width: 100%;
        padding: 12px;
        font-size: 16px;
        background-color: #007bff;
        color: white;
        border: none;
        border-radius: 8px;
        cursor: pointer;
    }
</style>

<div class="form-container">
    <h2>Edit Car Inspection Report</h2>
    <form action="{{ route('cars.update', $car->id) }}" method="POST" enctype="multipart/form-data" onsubmit="saveSketchData()">
    @csrf
    @method('PUT')

        {{-- Reuse all form fields with pre-filled values --}}
        @php
            $fields = [
                'make', 'model', 'reg_year', 'varient', 'engine_capacity', 'mileage',
                'fuel_type', 'inspection_date', 'chassis_no', 'engine_no', 'registration_no',
                'location', 'registered_city', 'color', 'demond', 
            ];
        @endphp

        @foreach($fields as $field)
        <div class="form-group">
            <label for="{{ $field }}">{{ ucfirst(str_replace('_', ' ', $field)) }}:</label>
            <input type="{{ $field === 'inspection_date' ? 'date' : 'text' }}" 
                   id="{{ $field }}" name="{{ $field }}" value="{{ old($field, $field === 'inspection_date' ? \Carbon\Carbon::parse($car->$field)->format('Y-m-d') : $car->$field) }}"  required>
        </div>
        @endforeach

        <div class="form-group" id="purchase_price" >
            <label for="purchase_price">Purchase Price:</label>
            <input  type="text" id="purchase_price" name="purchase_price" 
                value="{{ old('purchase_price', $car->purchase_price ?? '') }}">
        </div>
        
        {{-- Transmission dropdown --}}
        <div class="form-group">
            <label for="transmission">Transmission Type:</label>
            <select id="transmission" name="transmission">
                <option value="">Select Transmission</option>
                @foreach($transmissionTypes as $type)
                    <option value="{{ $type->transmission_type }}"
                        {{ $car->transmission == $type->transmission_type ? 'selected' : '' }}>
                        {{ $type->transmission_type }}
                    </option>
                @endforeach
            </select>
        </div>

        <!-- <div class="form-group">
            <label for="investor_id">Owner:</label>
            <select id="investor_id" name="investor_id" class="form-control" required>
                <option value="">Select Owner</option>
                @foreach($investors as $investor)
                    <option value="{{ $investor->id }}"
                        {{ $car->investor_id == $investor->id ? 'selected' : '' }}>
                        {{ $investor->name }} ({{ $investor->cnic }})
                    </option>
                @endforeach
            </select>
        </div>

        <div class="form-group" id="invester_price" style="display: none;">
            <label for="invester_price">Owner Price:</label>
            <input  type="text" id="invester_price" name="invester_price" 
                value="{{ old('invester_price', $car->invester_price ?? '') }}">
        </div>

        <script>
            function toggleInvestorPrice() {
                let investorSelect = document.getElementById('investor_id');
                let investorField = document.getElementById('invester_price');
                if (investorSelect.value === "") {
                    investorField.style.display = "none"; 
                } else {
                    investorField.style.display = "block"; 
                }
            }

            // Run once on page load
            toggleInvestorPrice();

            // Run every time the selection changes
            document.getElementById('investor_id').addEventListener('change', toggleInvestorPrice);
        </script> -->


        {{-- Inspector Comments --}}
        <div class="comments-section">
            <label for="inspector_comments">Inspector Comments:</label>
            <textarea class="form-control" name="inspector_comments" id="inspector_comments" rows="1">{{ old('inspector_comments', $car->inspector_comments) }}</textarea>
        </div>

        {{-- General Comments  --}}
        <div class="comments-section">
            <label for="general_comments">General Comments:</label>
            <textarea name="general_comments" id="general_comments" rows="2" class="form-control">{{ old('general_comments', $car->general_comments) }}</textarea>
        </div>

        {{-- Sketch Section --}}
        <div class="sketch-section">
            <label for="exterior_sketch">Exterior Condition (Sketch):</label>
            <div id="sketch-area-container" style="border:1px solid #ccc; width:100%; height:300px;">
                <canvas id="sketch-area" width="700" height="300"></canvas>
            </div>
            <input type="hidden" name="exterior_sketch_data" value="{{ old('exterior_sketch_data', $car->exterior_sketch_data) }}" id="exterior_sketch_data">
        </div>
        <br><br>



        {{-- Upload Pictures (optional for update) --}}
<div class="form-control">
    <label style="width: 100%; font-weight: bold;">Upload New Pictures (Optional):</label>
    <input type="file" id="multiUpload" name="pictures[]" class="form-control-file" multiple accept="image/*">
    <div class="row mt-3" id="previewContainer">
        @for($i = 1; $i <= 10; $i++)
            <div class="col-md-2 mb-3">
                <img id="preview{{ $i }}" src="" class="img-thumbnail" style="display:none; max-width:100%; height:100px;">
                <small>Image {{ $i }}</small>
            </div>
        @endfor
    </div>
</div>

<script>
document.getElementById('multiUpload').addEventListener('change', function(event) {
    let files = event.target.files;

    for (let i = 0; i < 10; i++) {
        let preview = document.getElementById('preview' + (i+1));
        if (files[i]) {
            let reader = new FileReader();
            reader.onload = function(e) {
                preview.src = e.target.result;
                preview.style.display = "block";
            };
            reader.readAsDataURL(files[i]);
        } else {
            preview.src = "";
            preview.style.display = "none";
        }
    }
});
</script>


        <button type="submit">Update Report</button>
    </form>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/5.2.4/fabric.min.js"></script>

<style>
    #optionMenu {
        position: absolute;
        background-color: white;
        border: 1px solid #ccc;
        z-index: 9999;
        padding: 5px;
        display: none;
        box-shadow: 0 2px 5px rgba(0,0,0,0.2);
    }

    #optionMenu button {
        display: block;
        width: 100%;
        background: none;
        border: none;
        padding: 5px 10px;
        text-align: left;
        cursor: pointer;
    }

    #optionMenu button:hover {
        background-color: #f0f0f0;
    }
</style>

<!-- Custom dropdown menu for labels -->
<div id="optionMenu">
    <button onclick="addLabel('S')">S</button>
    <button onclick="addLabel('SF')">SF</button>
    <button onclick="addLabel('MS')">MS</button>
    <button onclick="addLabel('P')">P</button>
    <button onclick="addLabel('D')">D</button>
</div>





<style>
    #optionMenu {
        position: absolute;
        background-color: white;
        border: 1px solid #ccc;
        z-index: 9999;
        padding: 5px;
        display: none;
        box-shadow: 0 2px 5px rgba(0,0,0,0.2);
    }

    #optionMenu button {
        display: block;
        width: 100%;
        background: none;
        border: none;
        padding: 5px 10px;
        text-align: left;
        cursor: pointer;
    }

    #optionMenu button:hover {
        background-color: #f0f0f0;
    }
</style>

<!-- Custom dropdown menu for labels -->
<div id="optionMenu">
    <button onclick="addLabel('S')">S</button>
    <button onclick="addLabel('SF')">SF</button>
    <button onclick="addLabel('MS')">MS</button>
    <button onclick="addLabel('P')">P</button>
    <button onclick="addLabel('D')">D</button>
</div>

<script>
    const canvas = new fabric.Canvas('sketch-area', {
        isDrawingMode: false
    });

    // Load background image (e.g., car outline)
// Load background image (car outline)
// Function to load background image
function loadBackground() {
    fabric.Image.fromURL("{{ url('car-outline.png') }}", function(img) {
        canvas.setBackgroundImage(img, canvas.renderAll.bind(canvas), {
            scaleX: canvas.width / img.width,
            scaleY: canvas.height / img.height,
            originX: 'left',
            originY: 'top'
        });
    });
}

// 🔹 Load stored sketch JSON if available
let storedData = document.getElementById('exterior_sketch_data').value;
if (storedData) {
    try {
        canvas.loadFromJSON(storedData, function () {
            loadBackground(); // put background back AFTER JSON load
            canvas.renderAll();
        });
    } catch (e) {
        console.error("Failed to load sketch data", e);
        loadBackground();
    }
} else {
    loadBackground();
}





// fabric.Image.fromURL("{{ asset('car-outline.png') }}", 
// function(img) {
//      img.set({
//          selectable: false, 
//          scaleX: canvas.width / img.width, 
//          scaleY: canvas.height / img.height 
//     }); 
//      canvas.add(img); canvas.sendToBack(img); 
// });


    let clickPos = null;
    const optionMenu = document.getElementById('optionMenu');
    let menuVisible = false;

    // Show menu on canvas click
    canvas.on('mouse:down', function (options) {
        const pointer = canvas.getPointer(options.e);
        clickPos = pointer;

        optionMenu.style.left = (options.e.pageX + 5) + 'px';
        optionMenu.style.top = (options.e.pageY + 5) + 'px';
        optionMenu.style.display = 'block';
        menuVisible = true;

        options.e.preventDefault();
        options.e.stopPropagation();
    });

    // Add selected label to canvas
    function addLabel(label) {
        const text = new fabric.Text(label, {
            left: clickPos.x,
            top: clickPos.y,
            fill: 'red',
            fontSize: 16,
            fontWeight: 'bold',
            selectable: true
        });
        canvas.add(text);
        optionMenu.style.display = 'none';
        menuVisible = false;
    }

    // Hide menu when clicking outside
    window.addEventListener('mousedown', function(e) {
        if (menuVisible && !optionMenu.contains(e.target)) {
            setTimeout(() => {
                optionMenu.style.display = 'none';
                menuVisible = false;
            }, 100); // slight delay allows menu click
        }
    });

    function saveSketchData() {
    document.getElementById('exterior_sketch_data').value = JSON.stringify(canvas.toJSON());
    }    

    // Save canvas JSON on form submit
    // document.querySelector('form').addEventListener('submit', function(e) {
    //     document.getElementById('exterior_sketch_data').value = JSON.stringify(canvas.toJSON());
    // });
</script>


@endsection




