@extends('admin.layouts.main-layout')
<?php if (!empty($project->encrypted_id)) {
    $title = 'Edit Project';
} else {
    $title = 'Add Project';
}
?>
@section('title', $title)

@section('content')
    <!-- Content wrapper -->
    <div class="content-wrapper">
        <!-- Content -->
        <div class="container-xxl flex-grow-1 container-p-y">
            <form
                action="{{ !empty($project->encrypted_id) ? route('edit.project', ['project' => $project->encrypted_id]) : route('add.project') }}"
                method="POST" enctype="multipart/form-data">
                @csrf
                <!-- Hoverable Table rows -->
                <h5 class="card-header"><?= $title ?><span class="float-end"><a href="{{ route('manage.projects') }}"
                            class="btn btn-icon rounded-pill btn-outline-secondary float-end"><i class='bx bx-left-arrow-alt'
                                style="font-size: 1.7rem;"></i></a></span></h5>
                <div class="row">
                    <div class="col-12">
                        @if (session('error'))
                            <div class="alert alert-danger alert-dismissible" role="alert">
                                {{ session('error') }}
                                <button type="button" class="btn-close" data-bs-dismiss="alert"
                                    aria-label="Close"></button>
                            </div>
                        @endif
                        <div class="card mb-4">
                            <div class="card-body">
                                <div class="row">
                                    <div class="col-6">
                                        <label for="subject_id" class="form-label">Subject</label>
                                        <select name="subject_id" id="subject_id" class="form-select">
                                            <option value="">-- Select Subject --</option>
                                            @foreach ($all_subjects as $subject)
                                                @if (!empty($project->encrypted_id))
                                                    <option value="{{ $subject->encrypted_id }}"
                                                        {{ $project->subject_id == $subject->id ? 'selected' : '' }}>
                                                        {{ $subject->subject_code . ' (' . $subject->subject_name . ')' }}
                                                    </option>
                                                @else
                                                    <option value="{{ $subject->encrypted_id }}">
                                                        {{ $subject->subject_code . ' (' . $subject->subject_name . ')' }}
                                                    </option>
                                                @endif
                                            @endforeach
                                        </select>
                                        @error('subject_id')
                                            <div class="text-danger">{{ $message }}</div>
                                        @enderror
                                    </div>
                                    <div class="col-6">
                                        <label for="type_ids" class="form-label">Type PDF(s)</label>
                                        <select name="type_ids[]" id="type_ids" class="form-select" multiple>
                                            @php
                                                $selectedTypes = !empty($project->encrypted_id)
                                                    ? $project->types->pluck('id')->toArray()
                                                    : [];
                                            @endphp
                                            @foreach ($all_project_types as $project_type)
                                                <option value="{{ $project_type->encrypted_id }}"
                                                    {{ in_array($project_type->id, $selectedTypes) ? 'selected' : '' }}>
                                                    {{ $project_type->type_name }}
                                                </option>
                                            @endforeach
                                        </select>
                                        @error('type_ids')
                                            <div class="text-danger">{{ $message }}</div>
                                        @enderror
                                    </div>
                                    <div class="col-6">
                                        <label for="language_ids" class="form-label">Medium</label>
                                        @php
                                            $selectedLanguages = !empty($project->encrypted_id)
                                                ? $project->languages->pluck('id')->toArray()
                                                : [];
                                        @endphp
                                        <select name="language_ids[]" id="language_ids" class="form-select" multiple>
                                            @foreach ($all_project_languages as $project_language)
                                                <option value="{{ $project_language->encrypted_id }}"
                                                    {{ in_array($project_language->id, $selectedLanguages) ? 'selected' : '' }}>
                                                    {{ $project_language->language_name }}
                                                </option>
                                            @endforeach
                                        </select>
                                        @error('language_ids')
                                            <div class="text-danger">{{ $message }}</div>
                                        @enderror
                                    </div>
                                    {{-- <div class="col-6">
                                        <label for="session_ids" class="form-label">Session(s)</label>
                                        @php
                                            $selectedSessions = !empty($project->encrypted_id)
                                                ? $project->sessions->pluck('id')->toArray()
                                                : [];
                                        @endphp
                                        <select name="session_ids[]" id="session_ids" class="form-select" multiple>
                                            @foreach ($all_project_sessions as $project_session)
                                                <option value="{{ $project_session->encrypted_id }}"
                                                    {{ in_array($project_session->id, $selectedSessions) ? 'selected' : '' }}>
                                                    {{ $project_session->session_name }}
                                                </option>
                                            @endforeach
                                        </select>
                                        @error('session_ids')
                                            <div class="text-danger">{{ $message }}</div>
                                        @enderror
                                    </div> --}}
                                    <div class="col-6">
                                        <label for="coupon_ids" class="form-label">Coupon(s)</label>
                                        @php
                                            $selectedCoupons = !empty($project->encrypted_id)
                                                ? $project->coupons->pluck('id')->toArray()
                                                : [];
                                        @endphp
                                        <select name="coupon_ids[]" id="coupon_ids" class="form-select" multiple>
                                            @foreach ($all_project_coupons as $project_coupon)
                                                <option value="{{ $project_coupon->encrypted_id }}"
                                                    {{ in_array($project_coupon->id, $selectedCoupons) ? 'selected' : '' }}>
                                                    <strong>{{ $project_coupon->coupon }}
                                                        <small>{{ $project_coupon->coupon_name }}</small>
                                                    </strong>
                                                </option>
                                            @endforeach
                                        </select>
                                        @error('coupon_ids')
                                            <div class="text-danger">{{ $message }}</div>
                                        @enderror
                                    </div>
                                    {{-- <div class="col-6">
                                        <label for="reference_number" class="col-form-label">Project Reference
                                            Number</label>
                                        <input type="text" class="form-control" id="reference_number"
                                            name="reference_number"
                                            value="{{ !empty($project->encrypted_id) ? $project->reference_number : old('reference_number') }}"
                                            oninput="this.value = this.value.replace(/[^0-9]/g, '');"
                                            placeholder="Enter Reference Number" />
                                        @error('reference_number')
                                            <div class="text-danger">{{ $message }}</div>
                                        @enderror
                                    </div> --}}
                                    <div class="col-6">
                                        <label for="topics" class="form-label">Topic(s)</label>
                                        <input type="text" class="form-control" id="topics" name="topics"
                                            value="{{ !empty($project->encrypted_id) && is_array($project->topics) ? implode(', ', $project->topics) : old('topics') }}"
                                            placeholder="Add Multiple Topics with Commas" />
                                        @error('topics')
                                            <div class="text-danger">{{ $message }}</div>
                                        @enderror
                                    </div>
                                    <div class="col-6">
                                        <label for="project_code" class="col-form-label">Project Code</label>
                                        <input type="text" class="form-control" id="project_code" name="project_code"
                                            value="{{ !empty($project->encrypted_id) ? $project->project_code : old('project_code') }}"
                                            oninput="this.value = this.value.replace(/[^A-Za-z0-9-]/g, '')"
                                            placeholder="Enter Code" onblur="getUrl(this.id)" />
                                        @error('project_code')
                                            <div class="text-danger">{{ $message }}</div>
                                        @enderror
                                    </div>
                                    <div class="col-6">
                                        <label for="project_subject_name" class="col-form-label">Project Subject
                                            Name</label>
                                        <input type="text" class="form-control" id="project_subject_name"
                                            name="project_subject_name"
                                            value="{{ !empty($project->encrypted_id) ? $project->project_subject_name : old('project_subject_name') }}"
                                            placeholder="Enter Name" />
                                        @error('project_subject_name')
                                            <div class="text-danger">{{ $message }}</div>
                                        @enderror
                                    </div>
                                    <div class="col-6">
                                        <label for="project_url" class="col-form-label">Project URL</label>
                                        <input type="text" class="form-control" id="project_url" name="project_url"
                                            value="{{ !empty($project->encrypted_id) ? $project->project_url : old('project_url') }}"
                                            placeholder="Enter URL" />
                                        @error('project_url')
                                            <div class="text-danger">{{ $message }}</div>
                                        @enderror
                                    </div>
                                    <div class="col-6">
                                        <label for="project_title" class="col-form-label">Project Title</label>
                                        <input type="text" class="form-control" id="project_title"
                                            name="project_title"
                                            value="{{ !empty($project->encrypted_id) ? $project->project_title : old('project_title') }}"
                                            placeholder="Enter Title" />
                                        @error('project_title')
                                            <div class="text-danger">{{ $message }}</div>
                                        @enderror
                                    </div>
                                    <div class="col-6">
                                        <label for="breadcrumb_headline" class="col-form-label">Breadcrumb
                                            Headline</label>
                                        <input type="text" class="form-control" id="breadcrumb_headline"
                                            name="breadcrumb_headline"
                                            value="{{ !empty($project->encrypted_id) ? $project->breadcrumb_headline : old('breadcrumb_headline') }}"
                                            placeholder="Enter Headline" />
                                        @error('breadcrumb_headline')
                                            <div class="text-danger">{{ $message }}</div>
                                        @enderror
                                    </div>
                                    <div class="col-6">
                                        <label for="project_quantity" class="col-form-label">Project
                                            Quantity</label>
                                        <input type="text" class="form-control" id="project_quantity"
                                            name="project_quantity"
                                            value="{{ !empty($project->encrypted_id) ? $project->project_quantity : old('project_quantity') }}"
                                            placeholder="Enter Quantity"
                                            oninput="this.value = this.value.replace(/[^0-9]/g, '');" />
                                        @error('project_quantity')
                                            <div class="text-danger">{{ $message }}</div>
                                        @enderror
                                    </div>
                                    <div class="col-6">
                                        <label for="maximum_retail_price" class="col-form-label">MRP</label>
                                        <input type="text" class="form-control" id="maximum_retail_price"
                                            name="maximum_retail_price"
                                            value="{{ !empty($project->encrypted_id) ? $project->maximum_retail_price : old('maximum_retail_price') }}"
                                            oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1').replace(/^(\d+\.\d{2}).*/g, '$1');"
                                            placeholder="Enter MRP" />
                                        @error('maximum_retail_price')
                                            <div class="text-danger">{{ $message }}</div>
                                        @enderror
                                    </div>
                                    <div class="col-6">
                                        <label for="selling_price" class="col-form-label">Selling Price</label>
                                        <input type="text" class="form-control" id="selling_price"
                                            name="selling_price"
                                            value="{{ !empty($project->encrypted_id) ? $project->selling_price : old('selling_price') }}"
                                            oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1').replace(/^(\d+\.\d{2}).*/g, '$1');"
                                            placeholder="Enter Selling Price" />
                                        @error('selling_price')
                                            <div class="text-danger">{{ $message }}</div>
                                        @enderror
                                    </div>
                                    <div class="col-6">
                                        <label for="discount" class="col-form-label">Discount (In %)</label>
                                        <input type="text" class="form-control" id="discount" name="discount"
                                            value="{{ !empty($project->encrypted_id) ? $project->discount : old('discount') }}"
                                            placeholder="Enter Discount"
                                            oninput="this.value = this.value.replace(/[^0-9]/g, '');" />
                                        @error('discount')
                                            <div class="text-danger">{{ $message }}</div>
                                        @enderror
                                    </div>
                                    <div class="col-6">
                                        <label for="additional_discount" class="col-form-label">Extra Discount (In
                                            %)</label>
                                        <input type="text" class="form-control" id="additional_discount"
                                            name="additional_discount"
                                            value="{{ !empty($project->encrypted_id) ? $project->additional_discount : old('additional_discount') }}"
                                            oninput="this.value = this.value.replace(/[^0-9]/g, '');"
                                            placeholder="Enter Extra Discount" />
                                        @error('additional_discount')
                                            <div class="text-danger">{{ $message }}</div>
                                        @enderror
                                    </div>
                                    <div class="col-6">
                                        <label for="discount_offer_expiry" class="col-form-label">Discount Expiry</label>
                                        <input type="datetime-local" class="form-control" id="discount_offer_expiry"
                                            name="discount_offer_expiry"
                                            value="{{ !empty($project->encrypted_id) && $project->discount_offer_expiry ? \Carbon\Carbon::parse($project->discount_offer_expiry)->format('Y-m-d\TH:i') : old('discount_offer_expiry') }}"
                                            placeholder="Enter Discount Expiry" />
                                        @error('discount_offer_expiry')
                                            <div class="text-danger">{{ $message }}</div>
                                        @enderror
                                    </div>
                                    <div class="col-6">
                                        <label for="project_expiry" class="col-form-label">Project Expiry</label>
                                        <input type="datetime-local" class="form-control" id="project_expiry"
                                            name="project_expiry"
                                            value="{{ !empty($project->encrypted_id) && $project->project_expiry ? \Carbon\Carbon::parse($project->project_expiry)->format('Y-m-d\TH:i') : old('project_expiry') }}"
                                            placeholder="Enter project Expiry" />
                                        @error('project_expiry')
                                            <div class="text-danger">{{ $message }}</div>
                                        @enderror
                                    </div>
                                    @if (!empty($project->encrypted_id))
                                        <div class="col-12">
                                            <label for="short_description" class="col-form-label">Short
                                                Description</label>
                                            <textarea id="short_description" name="short_description" class="form-control"
                                                placeholder="Enter Short Description">{{ !empty($project->encrypted_id) ? htmlspecialchars_decode($project->short_description) : '' }}</textarea>
                                        </div>
                                        <div class="col-12">
                                            <label for="download_info" class="col-form-label">Download Information</label>
                                            <textarea id="download_info" name="download_info" class="form-control" placeholder="Enter Download Information">{{ !empty($project->encrypted_id) ? htmlspecialchars_decode($project->download_info) : '' }}</textarea>
                                        </div>
                                        <div class="col-12">
                                            <label for="description" class="col-form-label">Description</label>
                                            <textarea id="description" name="description" class="form-control" placeholder="Enter Description">{{ !empty($project->encrypted_id) ? htmlspecialchars_decode($project->description) : '' }}</textarea>
                                        </div>
                                        <div class="col-12">
                                            <label for="cover_page_info" class="col-form-label">Cover Page
                                                Information</label>
                                            <textarea id="cover_page_info" name="cover_page_info" class="form-control" placeholder="Enter Cover Page Info">{{ !empty($project->encrypted_id) ? htmlspecialchars_decode($project->cover_page_info) : '' }}</textarea>
                                        </div>
                                    @endif
                                    <div class="col-6">
                                        <label for="meta_title" class="col-form-label">Meta Title</label>
                                        <input type="text" class="form-control" id="meta_title" name="meta_title"
                                            value="{{ !empty($project->encrypted_id) ? $project->meta_title : '' }}"
                                            placeholder="Enter Meta Title" />
                                    </div>
                                    <div class="col-6">
                                        <label for="meta_keyword" class="col-form-label">Meta Keyword</label>
                                        <input type="text" class="form-control" id="meta_keyword" name="meta_keyword"
                                            value="{{ !empty($project->encrypted_id) ? $project->meta_keyword : '' }}"
                                            placeholder="Enter Meta Keyword" />
                                    </div>
                                    <div class="col-12">
                                        <label for="meta_description" class="col-form-label">Meta Description</label>
                                        <textarea name="meta_description" id="meta_description" cols="30" rows="5" class="form-control"
                                            placeholder="Enter Meta Description">{{ !empty($project->encrypted_id) ? htmlspecialchars_decode($project->meta_description) : '' }}</textarea>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-6">
                                <div class="card mb-3">
                                    <div class="card-body">
                                        <label for="project_image" class="col-form-label">Project Image</label>
                                        @if (!empty($project->encrypted_id) && !empty($project->project_image))
                                            <div style="display: inline-block; position: relative; margin: 30px;"
                                                class="my-3">
                                                <img src="{{ asset($project->project_image) }}" alt="project_image"
                                                    class="rounded" height="60px" width="60px"
                                                    style="object-fit: cover;">
                                                <button
                                                    style="position: absolute; top: -5px; right: -5px; width: 20px; height: 20px; background: red; color: white; border: none; border-radius: 50%; font-size: 14px; cursor: pointer;">×</button>
                                            </div>
                                        @endif
                                        <input class="form-control" type="file" id="project_image"
                                            name="project_image" accept="image/*" />
                                    </div>
                                </div>
                            </div>
                            {{-- <div class="col-6">
                                <div class="card mb-3">
                                    <div class="card-body">
                                        <label for="question_paper_image" class="col-form-label">Question Paper
                                            Image</label>
                                        @if (!empty($project->encrypted_id) && !empty($project->question_paper_image))
                                            <div style="display: inline-block; position: relative; margin: 30px;"
                                                class="my-3">
                                                <img src="{{ asset($project->question_paper_image) }}"
                                                    alt="question_paper_image" class="rounded" height="60px"
                                                    width="60px" style="object-fit: cover;">
                                                <button
                                                    style="position: absolute; top: -5px; right: -5px; width: 20px; height: 20px; background: red; color: white; border: none; border-radius: 50%; font-size: 14px; cursor: pointer;">×</button>
                                            </div>
                                        @endif
                                        <input class="form-control" type="file" id="question_paper_image"
                                            name="question_paper_image" accept="image/*" />
                                    </div>
                                </div>
                            </div> --}}
                            <div class="col-6">
                                <div class="card mb-3">
                                    <div class="card-body">
                                        <label for="demo_file" class="col-form-label">Demo PDF (Optional)</label>
                                        @if (!empty($project->encrypted_id) && !empty($project->demo_file))
                                            <div style="display: inline-block; position: relative; margin: 30px;"
                                                class="my-3">
                                                <strong>Current Demo File:</strong>

                                                <p class="mb-2">
                                                    {{ basename($project->demo_file) }}
                                                </p>

                                                @if (file_exists(public_path($project->demo_file)))
                                                    <a href="{{ asset($project->demo_file) }}"
                                                        class="btn btn-sm btn-primary" download>
                                                        Download File
                                                    </a>
                                                @endif
                                                {{-- <button
                                                    style="position: absolute; top: -5px; right: -5px; width: 20px; height: 20px; background: red; color: white; border: none; border-radius: 50%; font-size: 14px; cursor: pointer;">×</button> --}}

                                                {{-- <button
                                                    type="button"
                                                    onclick="removeDemoPdf()"
                                                    style="position:absolute; top:-6px; right:-6px; width:22px; height:22px; 
                                                        background:red; color:white; border:none; border-radius:50%; 
                                                        font-size:14px; cursor:pointer; line-height:18px;">
                                                    ×
                                                </button>

                                                {{-- tells backend to delete on submit
                                                <input type="hidden" name="remove_demo_file" id="remove_demo_file" value="0"> --}}
                                            </div>
                                        @endif
                                        <input class="form-control" type="file" id="demo_file" name="demo_file"
                                            accept="application/pdf" />
                                        @error('demo_file')
                                            <div class="text-danger">{{ $message }}</div>
                                        @enderror
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-6">
                                <div class="card mb-3">
                                    <div class="card-body">
                                        <label for="project_file" class="col-form-label">Project File (Password
                                            Protected)</label>
                                        @if (!empty($project->encrypted_id) && !empty($project->project_file))
                                            <div style="display: inline-block; position: relative; margin: 30px;"
                                                class="my-3">
                                                <strong>Current Project File:</strong>

                                                <p class="mb-2">
                                                    {{ basename($project->project_file) }}
                                                </p>

                                                @if (file_exists(public_path($project->project_file)))
                                                    <a href="{{ asset($project->project_file) }}"
                                                        class="btn btn-sm btn-primary" download>
                                                        Download File
                                                    </a>
                                                @endif
                                                {{-- <button
                                                    style="position: absolute; top: -5px; right: -5px; width: 20px; height: 20px; background: red; color: white; border: none; border-radius: 50%; font-size: 14px; cursor: pointer;">×</button> --}}

                                                {{-- <button
                                                    type="button"
                                                    onclick="removeDemoPdf()"
                                                    style="position:absolute; top:-6px; right:-6px; width:22px; height:22px; 
                                                        background:red; color:white; border:none; border-radius:50%; 
                                                        font-size:14px; cursor:pointer; line-height:18px;">
                                                    ×
                                                </button>

                                                {{-- tells backend to delete on submit
                                                <input type="hidden" name="remove_project_file" id="remove_project_file" value="0"> --}}
                                            </div>
                                        @endif
                                        <input class="form-control" type="file" id="project_file" name="project_file"
                                            accept=".zip,.rar,.7zip" />
                                        @error('project_file')
                                            <div class="text-danger">{{ $message }}</div>
                                        @enderror
                                    </div>
                                </div>
                            </div>
                            <div class="col-6">
                                <div class="card mb-3">
                                    <div class="card-body">
                                        <label for="file_password" class="col-form-label">Project
                                            File Password</label>
                                        <input type="text" class="form-control" id="file_password"
                                            name="file_password"
                                            value="{{ !empty($project->encrypted_id) ? $project->file_password : old('file_password') }}"
                                            placeholder="Enter Password" />
                                        @error('file_password')
                                            <div class="text-danger">{{ $message }}</div>
                                        @enderror
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="demo-inline-spacing">
                            <input type="submit"
                                value="{{ !empty($project->encrypted_id) ? 'Update Project' : 'Add Project' }}"
                                class="btn btn-primary" />
                            <a href="{{ route('manage.projects') }}" class="btn btn-outline-secondary">Back</a>
                        </div>
                    </div>
                </div>
                <!--/ Hoverable Table rows -->
            </form>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            if (typeof $ === 'undefined' || !$.fn.select2) {
                console.error('Select2 or jQuery not loaded');
                return;
            }

            $('#subject_id').select2({
                placeholder: "Search subject...",
                allowClear: true,
                width: '100%'
            });
        });

        new MultiSelectTag('type_ids');
        new MultiSelectTag('language_ids');
        // new MultiSelectTag('session_ids');
        new MultiSelectTag('coupon_ids');
    </script>

    <script>
        function getUrl(field_id) {
            let errors = 0;
            let code = $.trim($("#" + field_id).val());
            let id = "{{ !empty($project->encrypted_id) ? $project->encrypted_id : '' }}";

            // Replace '/' and spaces with '-'
            let project_url = code.replace(/[\/\s]+/g, '-').toLowerCase();

            if (code == "" || code == undefined || code == null) {
                errors += 1;
            }
            if (project_url == "" || project_url == undefined || project_url == null) {
                errors += 1;
            }

            if (errors > 0) {
                $("#project_url").val("");
                return false;
            } else {
                // Remove invalid characters, trim extra dashes, and replace multiple dashes with a single dash
                project_url = project_url.replace(/[^a-z0-9-]+/g, '-').replace(/-+/g, '-').replace(/^-+|-+$/g, '');

                // Use Blade to generate the base route and append parameters dynamically
                let url = "{{ route('check.project.link', ['project_url' => '__LINK__', 'id' => '__ID__']) }}"
                    .replace('__LINK__', project_url)
                    .replace('__ID__', id);

                // Send GET request with parameters in the URL
                fetch(url)
                    .then(response => response.text()) // Expecting plain text response
                    .then(data => {
                        document.getElementById("project_url").value = data; // Update input field with returned link
                        // $("#project_url").val(data);
                    })
                    .catch(error => console.error("Error:", error));
            }
        }
    </script>

@endsection
