@extends('layouts.master')

@section('page-title') 
    Permits | {{ $page_title }}
@endsection

@section('page-css')
@endsection

@section('page-content')
@include('layouts.partials.navbar')
    <div class="container">
      <div class="row">
        
        <div class="col-md-12">
          <div class="mb-4">
                <h1 class="h3 mb-1">District Settings</h1>
                <p class="text-muted">Update these settings as needed</p>
            </div>

            <form id="districtSettingsForm" action="updatedistrictsettings" method="POST">
                @csrf 
                <div class="card shadow-sm mb-4">
                    <div class="card-header bg-white py-3">
                        <h5 class="card-title mb-0 text-dark">
                            <i class="bi bi-building me-2 text-secondary"></i>Assembly Profile
                        </h5>
                    </div>
                    <div class="card-body">
                        <div class="row mb-3 g-3">
                            <div class="col-md-6">
                                <label for="regionName" class="form-label fw-bold">Region Name</label>
                                <input type="text" class="form-control" id="regionName" name="region_name" value="" placeholder="e.g. Western Region" required >
                            </div>
                            <div class="col-md-6">
                                <label for="districtName" class="form-label fw-bold">District Name</label>
                                <input type="text" class="form-control" id="districtName" name="district_name" value="" placeholder="e.g. Sekondi-Takoradi Metropolitan Assembly" required>
                            </div>
                        </div>

                        <div class="row mb-3 g-3">
                            <div class="col-md-6">
                                <label for="assemblyType" class="form-label fw-bold">Assembly Type</label>
                                <select class="form-select" id="assemblyType" name="assembly_type" required>
                                    <option value="" selected disabled>Select assembly type...</option>
                                    <option value="metropolitan">Metropolitan</option>
                                    <option value="municipal">Municipal</option>
                                    <option value="district">District</option>
                                </select>
                            </div>
                            <div class="col-md-6">
                                <label for="abbreviation" class="form-label fw-bold">Abbreviation</label>
                                <input type="text" class="form-control" id="abbreviation" name="abbreviation" value="" placeholder="e.g. STMA" required>
                            </div>
                        </div>

                        <div class="row mb-3 g-3">
                            <div class="col-md-6">
                                <label for="contactPhone" class="form-label fw-bold">Contact Phone Number</label>
                                <input type="tel" class="form-control" id="contactPhone" name="contact_phone" value="" placeholder="e.g. 0554116836" required>
                            </div>
                            <div class="col-md-6">
                                <label for="contactEmail" class="form-label fw-bold">Contact Email</label>
                                <input type="email" class="form-control" id="contactEmail" name="contact_email" value="" placeholder="e.g. info@stma.gov.gh" required>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="card shadow-sm mb-4">
                    <div class="card-header bg-white py-3">
                        <h5 class="card-title mb-0 text-primary">
                            <i class="bi bi-envelope-fill me-2"></i>Email Notifications
                        </h5>
                    </div>
                    <div class="card-body">
                        <div class="mb-3">
                            <label for="outgoingEmail" class="form-label fw-bold">Outgoing Email Address</label>
                            <input type="email" class="form-control" id="outgoingEmail" name="outgoing_email" value="" placeholder="e.g. ppd@stma.gov.gh" required>
                        </div>
                        <div class="mb-3">
                            <label for="displayName" class="form-label fw-bold">Display Name</label>
                            <input type="text" class="form-control" id="displayName" name="display_name" value="" placeholder="e.g. Physical Planning Department" required>
                        </div>
                    </div>
                </div>

                <div class="card shadow-sm mb-4">
                    <div class="card-header bg-white py-3">
                        <h5 class="card-title mb-0 text-success">
                            <i class="bi bi-chat-left-text-fill me-2"></i>SMS Notifications
                        </h5>
                    </div>
                    <div class="card-body">
                        <div class="mb-3">
                            <label for="senderName" class="form-label fw-bold">Sender Name</label>
                            <input type="text" class="form-control" id="senderName" name="sms_sender_name" placeholder="e.g. STMA" value="" required>
                        </div>
                    </div>
                </div>

                <div class="d-grid gap-2 d-md-flex justify-content-md-end mb-5">
                    <button type="button" class="btn btn-outline-secondary px-4" id="cancelBtn">Cancel</button>
                    <button type="submit" class="btn btn-primary px-4" id="saveSettingsBtn">Save Changes</button>
                </div>
            </form>
        </div>
        
      </div>
    </div>

@endsection

@section('page-js')
<script type="text/javascript">
$(document).ready(function(){
    
    // 1. Load existing settings on page load
    fetchSettings();

    function fetchSettings() {
        $.ajax({
            // Ensure this route exists in your web.php
            url: '{{ url("admin/getdistrictsettingsjson") }}', 
            method: 'GET',
            success: function(response) {
                if(response.success && response.data) {
                    const data = response.data;
                    $('#regionName').val(data.region_name);
                    $('#districtName').val(data.district_name);
                    $('#assemblyType').val(data.assembly_type);
                    $('#abbreviation').val(data.abbreviation);
                    $('#contactPhone').val(data.contact_phone);
                    $('#contactEmail').val(data.contact_email);
                    $('#outgoingEmail').val(data.outgoing_email);
                    $('#displayName').val(data.display_name);
                    $('#senderName').val(data.sms_sender_name);
                }
            },
            error: function() {
                console.error("Could not load district settings.");
            }
        });
    }

    // 2. Handle form submission via AJAX
    $('#districtSettingsForm').on('submit', function(e) {
        e.preventDefault(); // Prevent standard page reload
        
        let $btn = $('#saveSettingsBtn');
        let originalText = $btn.html();
        
        // Show loading state on button
        $btn.html('<span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span>Saving...').prop('disabled', true);

        $.ajax({
            url: $(this).attr('action'), 
            method: 'POST',
            data: $(this).serialize(), // Automatically grabs all inputs and the @csrf token
            success: function(response) {
                if(response.success) {
                    // You can replace this with a Toastr or SweetAlert notification
                    $.alert('Settings updated successfully!'); 
                } else {
                    $.alert('Failed to update settings. Please try again.');
                }
            },
            error: function(xhr) {
                let errorMessage = 'An error occurred while saving.';
                // Optional: Handle Laravel validation errors returned as JSON
                if(xhr.responseJSON && xhr.responseJSON.errors) {
                    errorMessage = Object.values(xhr.responseJSON.errors)[0][0]; 
                }
                $.alert(errorMessage);
            },
            complete: function() {
                // Restore button state
                $btn.html(originalText).prop('disabled', false);
            }
        });
    });

    // Optional: Cancel button resets form to last saved database state
    $('#cancelBtn').on('click', function() {
        fetchSettings();
    });
});
</script>
@endsection