@extends('layouts.master')

@section('title', 'Company Info - Prolex Law Firm')

@section('content')
<style>
html, body {
    height: 100%;
    overflow-y: auto;
}

.table-scroll {
    max-height: 70vh;
    overflow-y: auto;
}

.table-scroll thead th {
    position: sticky;
    top: 0;
    background-color: white;
    z-index: 1;
}
</style>

<body id="page-top" style="padding-top: 0px;">

<!-- Page Wrapper -->
<div id="wrapper">

    <!-- Content Wrapper -->
    <div id="content-wrapper" class="d-flex flex-column">

        <!-- Main Content -->
        <div id="content">

            <!-- Begin Page Content -->

<div class="container-fluid py-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h4 class="fw-bold mb-0">
            <i class="fas fa-building me-2 text-primary"></i> Company Settings
        </h4>
        <a href="{{ route('dashboard') }}" class="btn btn-outline-primary">
            <i class="fas fa-arrow-left me-2"></i> Back to Admin
        </a>
    </div>

    <div id="company-display" class="card shadow-sm border-0 overflow-hidden">
        <div class="card-header bg-primary text-white py-3">
            <h5 class="mb-0"><i class="fas fa-info-circle me-2"></i> Company Information</h5>
        </div>

        <div class="card-body">

            <div class="row align-items-center mb-5">
                <div class="col-md-3 text-center">
                    <img id="company-logo" src="" alt="Company Logo" class="img-fluid rounded shadow-sm" style="max-height: 180px; display: none;">
                </div>
                <div class="col-md-9">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label text-muted small mb-1">Company Name</label>
                                <h4 class="fw-bold text-primary" id="display-company-name">Loading...</h4>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label text-muted small mb-1">Company Code</label>
                                <p class="fw-semibold" id="display-company-code">Loading...</p>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label text-muted small mb-1">Phone</label>
                                <p class="mb-0"><i class="fas fa-phone-alt me-2 text-muted"></i><span id="display-phone">Loading...</span></p>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label text-muted small mb-1">Email</label>
                                <p class="mb-0"><i class="fas fa-envelope me-2 text-muted"></i><span id="display-email">Loading...</span></p>
                            </div>
                        </div>
                    </div>

                    <div class="mb-3">
                        <label class="form-label text-muted small mb-1">Address</label>
                        <p class="mb-0"><i class="fas fa-map-marker-alt me-2 text-muted"></i><span id="display-address">Loading...</span></p>
                    </div>

                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label text-muted small mb-1">Website</label>
                                <p class="mb-0">
                                    <i class="fas fa-globe me-2 text-muted"></i>
                                    <span id="display-website">Loading...</span>
                                </p>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label text-muted small mb-1">Tax ID</label>
                                <p class="mb-0" id="display-tax-id">Loading...</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <h5 class="mb-3 border-bottom pb-2"><i class="fas fa-university me-2 text-primary"></i> Bank Details</h5>
            <div class="table-responsive">
                <table class="table table-hover align-middle">
                    <thead class="table-light">
                        <tr>
                            <th>Bank Name</th>
                            <th>Account Number</th>
                        </tr>
                    </thead>
                    <tbody id="display-bank-details-table">
                        <tr>
                            <td colspan="2" class="text-center">Loading...</td>
                        </tr>
                    </tbody>
                </table>
            </div>

            <div class="d-flex justify-content-end mt-4 pt-3 border-top">
                <button id="edit-company-info" class="btn btn-primary me-2">
                    <i class="fas fa-edit me-1"></i> Edit Settings
                </button>
            </div>
        </div>
    </div>

    <div class="mt-4 text-center">
        <p class="text-muted">Copyright © 2025 Prolex Law Firm</p>
    </div>
</div>

    <!-- Edit Form Card -->
    <div id="company-form" class="card shadow-sm border-0 overflow-hidden mt-4" style="display: none;">
        <div class="card-header bg-primary text-white py-3">
            <h5 class="mb-0"><i class="fas fa-edit me-2"></i> Edit Company Information</h5>
        </div>
        <div class="card-body">
            <form id="company-info-form">
                @csrf
                <div class="row">
                    <div class="col-md-6">
                        <div class="mb-3">
                            <label for="company_name" class="form-label">Company Name *</label>
                            <input type="text" id="company_name" name="company_name" class="form-control" required>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="mb-3">
                            <label for="company_code" class="form-label">Company Code *</label>
                            <input type="text" id="company_code" name="company_code" class="form-control" required>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-6">
                        <div class="mb-3">
                            <label for="phone" class="form-label">Phone</label>
                            <input type="tel" id="phone" name="phone" class="form-control">
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="mb-3">
                            <label for="email" class="form-label">Email</label>
                            <input type="email" id="email" name="email" class="form-control">
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-6">
                        <div class="mb-3">
                            <label for="website" class="form-label">Website</label>
                            <input type="url" id="website" name="website" class="form-control">
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="mb-3">
                            <label for="tax_id" class="form-label">Tax ID</label>
                            <input type="text" id="tax_id" name="tax_id" class="form-control">
                        </div>
                    </div>
                </div>
                <div class="mb-3">
                    <label for="logo_url" class="form-label">Logo URL</label>
                    <input type="url" id="logo_url" name="logo_url" class="form-control">
                </div>
                <div class="mb-3">
                    <label for="address" class="form-label">Address</label>
                    <textarea id="address" name="address" rows="3" class="form-control"></textarea>
                </div>
                <div class="mb-3">
                    <label class="form-label">Bank Details</label>
                    <div id="bank-details-container">
                        <!-- Bank details will be dynamically added here -->
                    </div>
                    <button type="button" id="add-bank-detail" class="btn btn-success btn-sm mt-2">
                        <i class="fas fa-plus me-1"></i>Add Bank Detail
                    </button>
                </div>
                <div class="d-flex justify-content-end">
                    <button type="button" id="cancel-edit" class="btn btn-secondary me-2">Cancel</button>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save me-1"></i>Save Company Information
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Custom CSS for animations and styling -->
<style>
@keyframes fadeInDown {
    from { opacity: 0; transform: translateY(-20px); }
    to { opacity: 1; transform: translateY(0); }
}
@keyframes fadeInUp {
    from { opacity: 0; transform: translateY(20px); }
    to { opacity: 1; transform: translateY(0); }
}
@keyframes fadeIn {
    from { opacity: 0; }
    to { opacity: 1; }
}

.animate-fadeInDown {
    animation: fadeInDown 1s forwards;
}
.animate-fadeInUp {
    animation: fadeInUp 1s forwards;
}
.animate-fadeIn {
    opacity: 0;
    animation: fadeIn 1s forwards;
}
.animate-fadeIn.delay-200 {
    animation-delay: 0.2s;
}
.animate-fadeIn.delay-400 {
    animation-delay: 0.4s;
}
</style>

<script>
document.addEventListener('DOMContentLoaded', function() {
    loadCompanyInfo();

    // Form submission
    document.getElementById('company-info-form').addEventListener('submit', function(e) {
        e.preventDefault();
        saveCompanyInfo();
    });

    // Add bank detail button
    document.getElementById('add-bank-detail').addEventListener('click', function() {
        addBankDetailField();
    });

    // Edit button
    document.getElementById('edit-company-info').addEventListener('click', function() {
        showForm();
    });

    // Cancel button
    document.getElementById('cancel-edit').addEventListener('click', function() {
        showDisplay();
    });
});

function loadCompanyInfo() {
    fetch('/administration/api/company-info')
        .then(response => response.json())
        .then(data => {
            if (data.company_name) {
                // Populate display
                populateDisplay(data);
                // Populate form
                populateForm(data);
                // Show display
                showDisplay();
            } else {
                // No data, use dummy data
                const dummyData = {
                    company_name: 'DAVIS AND MAINS',
                    company_code: 'comp222',
                    phone: '0777367773',
                    email: 'tadiwagwena@gmail.com',
                    website: 'https://davis.com',
                    tax_id: 'TXN231',
                    logo_url: 'https://media.licdn.com/dms/image/v2/C4E16AQEaX1EoB1ataw/profile-displaybackgroundimage-shrink_200_800/profile-displaybackgroundimage-shrink_200_800/0/1663195683531?e=2147483647&v=beta&t=9c4zc54wYNzNQmMuFKijKODnkJ6S48vpr0ceCfU1irw',
                    address: 'Machipisa, Old Highfield',
                    bank_details: [{ bank_name: 'cabs', account_number: '11122' }]
                };
                populateDisplay(dummyData);
                populateForm(dummyData);
                showDisplay();
            }
        })
        .catch(error => {
            console.error('Error loading company info:', error);
            // Use dummy data on error
            const dummyData = {
                company_name: 'DAVIS AND MAINS',
                company_code: 'comp222',
                phone: '0777367773',
                email: 'tadiwagwena@gmail.com',
                website: 'https://davis.com',
                tax_id: 'TXN231',
                logo_url: 'https://media.licdn.com/dms/image/v2/C4E16AQEaX1EoB1ataw/profile-displaybackgroundimage-shrink_200_800/profile-displaybackgroundimage-shrink_200_800/0/1663195683531?e=2147483647&v=beta&t=9c4zc54wYNzNQmMuFKijKODnkJ6S48vpr0ceCfU1irw',
                address: 'Machipisa, Old Highfield',
                bank_details: [{ bank_name: 'cabs', account_number: '11122' }]
            };
            populateDisplay(dummyData);
            populateForm(dummyData);
            showDisplay();
        });
}

function populateDisplay(data) {
    document.getElementById('display-company-name').textContent = data.company_name || 'N/A';
    document.getElementById('display-company-code').textContent = data.company_code || 'N/A';
    document.getElementById('display-phone').textContent = data.phone || 'N/A';
    document.getElementById('display-email').textContent = data.email || 'N/A';
    const websiteSpan = document.getElementById('display-website');
    if (data.website) {
        websiteSpan.innerHTML = `<a href="${data.website}" target="_blank">${data.website}</a>`;
    } else {
        websiteSpan.textContent = 'N/A';
    }
    document.getElementById('display-tax-id').textContent = data.tax_id || 'N/A';
    document.getElementById('display-address').textContent = data.address || 'N/A';

    // Show logo if available
    const logoImg = document.getElementById('company-logo');
    if (data.logo_url) {
        logoImg.src = data.logo_url;
        logoImg.style.display = 'block';
    } else {
        logoImg.style.display = 'none';
    }

    // Bank details
    const tbody = document.getElementById('display-bank-details-table');
    tbody.innerHTML = '';
    if (data.bank_details && Array.isArray(data.bank_details) && data.bank_details.length > 0) {
        data.bank_details.forEach(detail => {
            const tr = document.createElement('tr');
            tr.innerHTML = `
                <td>${detail.bank_name || 'N/A'}</td>
                <td>${detail.account_number || 'N/A'}</td>
            `;
            tbody.appendChild(tr);
        });
    } else {
        tbody.innerHTML = '<tr><td colspan="2" class="text-center">No bank details available</td></tr>';
    }
}

function populateForm(data) {
    document.getElementById('company_name').value = data.company_name || '';
    document.getElementById('company_code').value = data.company_code || '';
    document.getElementById('phone').value = data.phone || '';
    document.getElementById('email').value = data.email || '';
    document.getElementById('website').value = data.website || '';
    document.getElementById('tax_id').value = data.tax_id || '';
    document.getElementById('logo_url').value = data.logo_url || '';
    document.getElementById('address').value = data.address || '';

    // Load bank details
    loadBankDetails(data.bank_details || []);
}

function showDisplay() {
    document.getElementById('company-display').style.display = 'block';
    document.getElementById('company-form').style.display = 'none';
}

function showForm() {
    document.getElementById('company-display').style.display = 'none';
    document.getElementById('company-form').style.display = 'block';
}

function loadBankDetails(bankDetails) {
    const container = document.getElementById('bank-details-container');
    container.innerHTML = '';

    if (Array.isArray(bankDetails)) {
        bankDetails.forEach((detail, index) => {
            addBankDetailField(detail, index);
        });
    }
}

function addBankDetailField(detail = {}, index = null) {
    const container = document.getElementById('bank-details-container');
    const bankDetailDiv = document.createElement('div');
    bankDetailDiv.className = 'row mb-3 bank-detail-item';
    bankDetailDiv.innerHTML = `
        <div class="col-md-5">
            <input type="text" name="bank_details[${index !== null ? index : Date.now()}]" placeholder="Bank Name" value="${detail.bank_name || ''}" class="form-control">
        </div>
        <div class="col-md-5">
            <input type="text" name="account_number[${index !== null ? index : Date.now()}]" placeholder="Account Number" value="${detail.account_number || ''}" class="form-control">
        </div>
        <div class="col-md-2">
            <button type="button" class="btn btn-danger btn-sm remove-bank-detail">Remove</button>
        </div>
    `;

    bankDetailDiv.querySelector('.remove-bank-detail').addEventListener('click', function() {
        bankDetailDiv.remove();
    });

    container.appendChild(bankDetailDiv);
}

function saveCompanyInfo() {
    const formData = new FormData(document.getElementById('company-info-form'));

    // Process bank details
    const bankDetails = [];
    const bankDetailContainers = document.querySelectorAll('#bank-details-container .bank-detail-item');

    bankDetailContainers.forEach(container => {
        const bankName = container.querySelector('input[name^="bank_details"]').value.trim();
        const accountNumber = container.querySelector('input[name^="account_number"]').value.trim();

        if (bankName) {
            bankDetails.push({
                bank_name: bankName,
                account_number: accountNumber
            });
        }
    });

    const data = {
        company_name: formData.get('company_name'),
        company_code: formData.get('company_code'),
        phone: formData.get('phone'),
        email: formData.get('email'),
        website: formData.get('website'),
        tax_id: formData.get('tax_id'),
        logo_url: formData.get('logo_url'),
        address: formData.get('address'),
        bank_details: bankDetails
    };

    fetch('/administration/api/company-info', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
        },
        body: JSON.stringify(data)
    })
    .then(response => response.json())
    .then(savedData => {
        alert('Company information saved successfully!');
        console.log('Success:', savedData);

        // Reload and show display
        loadCompanyInfo();
    })
    .catch(error => {
        alert('Error saving company information. Please try again.');
        console.error('Error:', error);
    });
}
</script>
@endsection

