<?php
session_start();
include 'layouts/dbconn.php';
include 'includes/menu_config.php';

// Set timezone to East Africa Time
date_default_timezone_set('Africa/Nairobi');

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$user_id = $_SESSION['user_id'];

// Fetch user details
$sql_user = "SELECT u.*, ur.role_name FROM users u 
             INNER JOIN user_roles ur ON u.role_id = ur.role_id 
             WHERE u.user_id = ?";
$stmt_user = $conn->prepare($sql_user);
$stmt_user->bind_param("i", $user_id);
$stmt_user->execute();
$user_details = $stmt_user->get_result()->fetch_assoc();

if (!$user_details || $user_details['role_name'] !== 'Administrator') {
    header('Location: index.php');
    exit();
}

$full_name = $user_details['full_name'];
$role_name = $user_details['role_name'];

// Handle form submission
if ($_POST && isset($_POST['action'])) {
    header('Content-Type: application/json');
    
    try {
        $conn->begin_transaction();
        
        if ($_POST['action'] === 'update_company') {
            $updated_count = 0;
            
            $company_fields = [
                'company_name', 'company_address', 'company_city', 'company_state',
                'company_postal_code', 'company_country', 'company_phone', 
                'company_email', 'company_website', 'company_tax_id'
            ];
            
            foreach ($company_fields as $field) {
                if (isset($_POST[$field])) {
                    $value = trim($_POST[$field]);
                    
                    $sql_setting = "INSERT INTO settings (setting_key, setting_value, category, updated_at) 
                                   VALUES (?, ?, 'company', NOW()) 
                                   ON DUPLICATE KEY UPDATE 
                                   setting_value = VALUES(setting_value), 
                                   updated_at = NOW()";
                    
                    $stmt_setting = $conn->prepare($sql_setting);
                    $stmt_setting->bind_param("ss", $field, $value);
                    
                    if ($stmt_setting->execute()) {
                        $updated_count++;
                    }
                }
            }
            
            // Log activity
            $log_sql = "INSERT INTO activity_log (user_id, action, module, record_id, new_values) 
                       VALUES (?, 'UPDATE', 'settings', 'company_profile', ?)";
            $stmt_log = $conn->prepare($log_sql);
            $log_details = json_encode(['fields_updated' => $updated_count, 'timestamp' => date('Y-m-d H:i:s')]);
            $stmt_log->bind_param("is", $user_id, $log_details);
            $stmt_log->execute();
            
            $conn->commit();
            
            echo json_encode([
                'success' => true, 
                'message' => "Company profile updated successfully ($updated_count fields)"
            ]);
        }
        
        elseif ($_POST['action'] === 'upload_logo') {
            if (isset($_FILES['company_logo']) && $_FILES['company_logo']['error'] === UPLOAD_ERR_OK) {
                $upload_dir = 'uploads/company/';
                if (!is_dir($upload_dir)) {
                    mkdir($upload_dir, 0755, true);
                }
                
                $file_info = pathinfo($_FILES['company_logo']['name']);
                $allowed_types = ['jpg', 'jpeg', 'png', 'gif', 'svg'];
                
                if (!in_array(strtolower($file_info['extension']), $allowed_types)) {
                    throw new Exception('Invalid file type. Please upload JPG, PNG, GIF, or SVG files only.');
                }
                
                $file_name = 'logo_' . time() . '.' . $file_info['extension'];
                $file_path = $upload_dir . $file_name;
                
                if (move_uploaded_file($_FILES['company_logo']['tmp_name'], $file_path)) {
                    // Update database
                    $sql_logo = "INSERT INTO settings (setting_key, setting_value, category, updated_at) 
                                VALUES ('company_logo', ?, 'company', NOW()) 
                                ON DUPLICATE KEY UPDATE 
                                setting_value = VALUES(setting_value), 
                                updated_at = NOW()";
                    
                    $stmt_logo = $conn->prepare($sql_logo);
                    $stmt_logo->bind_param("s", $file_path);
                    $stmt_logo->execute();
                    
                    $conn->commit();
                    
                    echo json_encode([
                        'success' => true, 
                        'message' => 'Company logo uploaded successfully',
                        'logo_path' => $file_path
                    ]);
                } else {
                    throw new Exception('Failed to upload file');
                }
            } else {
                throw new Exception('No file uploaded or upload error occurred');
            }
        }
        
    } catch (Exception $e) {
        $conn->rollback();
        echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
    }
    exit();
}

// Fetch company settings
$sql_company = "SELECT setting_key, setting_value FROM settings 
                WHERE category = 'company' OR setting_key = 'company_logo'
                ORDER BY setting_key";
$result_company = $conn->query($sql_company);

$company_settings = [];
while ($row = $result_company->fetch_assoc()) {
    $company_settings[$row['setting_key']] = $row['setting_value'];
}

// Helper function
function getCompanySetting($key, $default = '') {
    global $company_settings;
    return $company_settings[$key] ?? $default;
}

$conn->close();
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Company Profile - Freight Management System')); ?>
    <?php include 'layouts/head-css.php'; ?>
    
    <!-- Remix Icons -->
    <link href="https://cdn.jsdelivr.net/npm/remixicon@3.5.0/fonts/remixicon.css" rel="stylesheet">
    
    <!-- SweetAlert2 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css" rel="stylesheet">
    
    <style>
        body {
            background-color: #f8fafc;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
        }
        
        .page-content {
            padding: 1.5rem;
        }
        
        .company-header {
            background: linear-gradient(135deg, #1e40af 0%, #3b82f6 100%);
            color: white;
            border-radius: 12px;
            padding: 2rem;
            margin-bottom: 2rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }
        
        .company-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            border: 1px solid #e3e6f0;
            margin-bottom: 1.5rem;
            overflow: hidden;
        }
        
        .company-card:hover {
            box-shadow: 0 4px 15px rgba(0,0,0,0.15);
            transform: translateY(-1px);
        }
        
        .card-header-custom {
            background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
            border-bottom: 1px solid #e2e8f0;
            padding: 1.5rem;
        }
        
        .card-title-custom {
            font-size: 1.125rem;
            font-weight: 600;
            color: #1e293b;
            margin: 0;
            display: flex;
            align-items: center;
        }
        
        .card-title-custom i {
            margin-right: 0.75rem;
            font-size: 1.25rem;
            color: #3b82f6;
        }
        
        .logo-upload-area {
            border: 2px dashed #d1d5db;
            border-radius: 12px;
            padding: 2rem;
            text-align: center;
            transition: all 0.3s ease;
            cursor: pointer;
            position: relative;
            background: #fafafa;
        }
        
        .logo-upload-area:hover {
            border-color: #3b82f6;
            background: #f0f9ff;
        }
        
        .logo-upload-area.dragover {
            border-color: #1e40af;
            background: #dbeafe;
            transform: scale(1.02);
        }
        
        .current-logo {
            max-width: 200px;
            max-height: 100px;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            margin-bottom: 1rem;
        }
        
        .logo-upload-icon {
            font-size: 3rem;
            color: #6b7280;
            margin-bottom: 1rem;
        }
        
        .upload-text {
            color: #374151;
            font-weight: 500;
            margin-bottom: 0.5rem;
        }
        
        .upload-hint {
            color: #6b7280;
            font-size: 0.875rem;
        }
        
        .form-group {
            margin-bottom: 1.5rem;
        }
        
        .form-label {
            font-weight: 600;
            color: #374151;
            margin-bottom: 0.5rem;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .form-label i {
            color: #3b82f6;
            font-size: 0.875rem;
        }
        
        .form-control {
            border-radius: 8px;
            border: 1px solid #d1d5db;
            padding: 0.75rem 1rem;
            transition: all 0.2s ease;
        }
        
        .form-control:focus {
            border-color: #3b82f6;
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
        }
        
        .form-text {
            color: #6b7280;
            font-size: 0.875rem;
            margin-top: 0.5rem;
        }
        
        .save-button {
            background: linear-gradient(45deg, #10b981, #059669);
            color: white;
            border: none;
            padding: 0.75rem 2rem;
            border-radius: 8px;
            font-weight: 600;
            transition: all 0.3s ease;
            box-shadow: 0 4px 15px rgba(16, 185, 129, 0.3);
        }
        
        .save-button:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(16, 185, 129, 0.4);
            color: white;
        }
        
        .company-preview {
            background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
            border: 1px solid #0ea5e9;
            border-radius: 12px;
            padding: 1.5rem;
            text-align: center;
        }
        
        .preview-logo {
            max-width: 120px;
            max-height: 60px;
            margin-bottom: 1rem;
        }
        
        .preview-company-name {
            font-size: 1.25rem;
            font-weight: 700;
            color: #0c4a6e;
            margin-bottom: 0.5rem;
        }
        
        .preview-details {
            color: #0369a1;
            font-size: 0.875rem;
            line-height: 1.5;
        }
        
        .info-icon {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            width: 20px;
            height: 20px;
            border-radius: 50%;
            background: #dbeafe;
            color: #1e40af;
            font-size: 0.75rem;
            cursor: help;
        }
        
        .grid-2 {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 1.5rem;
        }
        
        @media (max-width: 768px) {
            .page-content {
                padding: 1rem;
            }
            
            .company-header {
                padding: 1.5rem;
            }
            
            .grid-2 {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    
                    <!-- Page Header -->
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0"><i class="ri-building-line me-2"></i>Company Profile</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="index.php">Dashboard</a></li>
                                        <li class="breadcrumb-item"><a href="system_settings.php">System</a></li>
                                        <li class="breadcrumb-item active">Company Profile</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Company Header -->
                    <div class="company-header">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h2 class="mb-2">
                                    <i class="ri-building-2-line me-2"></i>Company Information
                                </h2>
                                <p class="mb-0 opacity-90">Manage your company profile and branding information</p>
                            </div>
                            <div class="text-end">
                                <div class="fw-bold">System Admin</div>
                                <div class="opacity-80"><?php echo $full_name; ?></div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <!-- Company Logo Section -->
                        <div class="col-xl-4 col-lg-5">
                            <div class="company-card">
                                <div class="card-header-custom">
                                    <h5 class="card-title-custom">
                                        <i class="ri-image-line"></i>Company Logo
                                    </h5>
                                </div>
                                <div class="card-body p-4">
                                    <form id="logoUploadForm" enctype="multipart/form-data">
                                        <div class="logo-upload-area" id="logoUploadArea" onclick="document.getElementById('logoFileInput').click()">
                                            <?php if (getCompanySetting('company_logo')): ?>
                                                <img src="<?php echo htmlspecialchars(getCompanySetting('company_logo')); ?>" 
                                                     alt="Current Logo" class="current-logo" id="currentLogo">
                                                <div class="upload-text">Click to change logo</div>
                                            <?php else: ?>
                                                <div class="logo-upload-icon">
                                                    <i class="ri-image-add-line"></i>
                                                </div>
                                                <div class="upload-text">Click to upload logo</div>
                                            <?php endif; ?>
                                            <div class="upload-hint">Drag and drop or click to select</div>
                                            <div class="upload-hint mt-2">Recommended: 300x150px, PNG/JPG format</div>
                                        </div>
                                        <input type="file" id="logoFileInput" name="company_logo" accept="image/*" style="display: none;">
                                        <input type="hidden" name="action" value="upload_logo">
                                    </form>
                                    
                                    <div class="mt-4">
                                        <h6>Logo Guidelines:</h6>
                                        <ul class="text-muted small">
                                            <li>Maximum file size: 2MB</li>
                                            <li>Supported formats: PNG, JPG, GIF, SVG</li>
                                            <li>Transparent background recommended</li>
                                            <li>High resolution for print materials</li>
                                        </ul>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Company Preview -->
                            <div class="company-card">
                                <div class="card-header-custom">
                                    <h5 class="card-title-custom">
                                        <i class="ri-eye-line"></i>Preview
                                    </h5>
                                </div>
                                <div class="card-body p-4">
                                    <div class="company-preview" id="companyPreview">
                                        <?php if (getCompanySetting('company_logo')): ?>
                                            <img src="<?php echo htmlspecialchars(getCompanySetting('company_logo')); ?>" 
                                                 alt="Company Logo" class="preview-logo" id="previewLogo">
                                        <?php endif; ?>
                                        <div class="preview-company-name" id="previewName">
                                            <?php echo htmlspecialchars(getCompanySetting('company_name', 'Your Company Name')); ?>
                                        </div>
                                        <div class="preview-details" id="previewDetails">
                                            <div id="previewAddress"><?php echo htmlspecialchars(getCompanySetting('company_address', 'Company Address')); ?></div>
                                            <div id="previewCityCountry">
                                                <?php echo htmlspecialchars(getCompanySetting('company_city', 'City')); ?>, 
                                                <?php echo htmlspecialchars(getCompanySetting('company_country', 'Country')); ?>
                                            </div>
                                            <div id="previewContact" class="mt-2">
                                                <div id="previewPhone"><?php echo htmlspecialchars(getCompanySetting('company_phone', 'Phone Number')); ?></div>
                                                <div id="previewEmail"><?php echo htmlspecialchars(getCompanySetting('company_email', 'email@company.com')); ?></div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Company Details Form -->
                        <div class="col-xl-8 col-lg-7">
                            <div class="company-card">
                                <div class="card-header-custom">
                                    <h5 class="card-title-custom">
                                        <i class="ri-building-line"></i>Company Details
                                    </h5>
                                </div>
                                <div class="card-body p-4">
                                    <form id="companyForm">
                                        <div class="grid-2">
                                            <div class="form-group">
                                                <label for="company_name" class="form-label">
                                                    <i class="ri-building-2-line"></i>Company Name *
                                                    <span class="info-icon" title="Legal company name as registered">i</span>
                                                </label>
                                                <input type="text" class="form-control" id="company_name" name="company_name" 
                                                       value="<?php echo htmlspecialchars(getCompanySetting('company_name', 'Polakis Technologies Ltd')); ?>" 
                                                       required onchange="updatePreview()">
                                                <div class="form-text">This will appear on all official documents</div>
                                            </div>
                                            
                                            <div class="form-group">
                                                <label for="company_tax_id" class="form-label">
                                                    <i class="ri-file-text-line"></i>Tax ID / Registration Number
                                                </label>
                                                <input type="text" class="form-control" id="company_tax_id" name="company_tax_id" 
                                                       value="<?php echo htmlspecialchars(getCompanySetting('company_tax_id', '')); ?>">
                                                <div class="form-text">Business registration or tax identification number</div>
                                            </div>
                                            
                                            <div class="form-group">
                                                <label for="company_address" class="form-label">
                                                    <i class="ri-map-pin-line"></i>Street Address *
                                                </label>
                                                <input type="text" class="form-control" id="company_address" name="company_address" 
                                                       value="<?php echo htmlspecialchars(getCompanySetting('company_address', 'Nanak House, Kimathi Street')); ?>" 
                                                       required onchange="updatePreview()">
                                            </div>
                                            
                                            <div class="form-group">
                                                <label for="company_city" class="form-label">
                                                    <i class="ri-building-3-line"></i>City *
                                                </label>
                                                <input type="text" class="form-control" id="company_city" name="company_city" 
                                                       value="<?php echo htmlspecialchars(getCompanySetting('company_city', 'Nairobi')); ?>" 
                                                       required onchange="updatePreview()">
                                            </div>
                                            
                                            <div class="form-group">
                                                <label for="company_state" class="form-label">
                                                    <i class="ri-map-2-line"></i>State/Province
                                                </label>
                                                <input type="text" class="form-control" id="company_state" name="company_state" 
                                                       value="<?php echo htmlspecialchars(getCompanySetting('company_state', 'Nairobi')); ?>">
                                            </div>
                                            
                                            <div class="form-group">
                                                <label for="company_postal_code" class="form-label">
                                                    <i class="ri-mail-line"></i>Postal Code
                                                </label>
                                                <input type="text" class="form-control" id="company_postal_code" name="company_postal_code" 
                                                       value="<?php echo htmlspecialchars(getCompanySetting('company_postal_code', '00100')); ?>">
                                            </div>
                                            
                                            <div class="form-group">
                                                <label for="company_country" class="form-label">
                                                    <i class="ri-global-line"></i>Country *
                                                </label>
                                                <select class="form-control" id="company_country" name="company_country" required onchange="updatePreview()">
                                                    <option value="Kenya" <?php echo getCompanySetting('company_country', 'Kenya') == 'Kenya' ? 'selected' : ''; ?>>Kenya</option>
                                                    <option value="Uganda" <?php echo getCompanySetting('company_country') == 'Uganda' ? 'selected' : ''; ?>>Uganda</option>
                                                    <option value="Tanzania" <?php echo getCompanySetting('company_country') == 'Tanzania' ? 'selected' : ''; ?>>Tanzania</option>
                                                    <option value="Rwanda" <?php echo getCompanySetting('company_country') == 'Rwanda' ? 'selected' : ''; ?>>Rwanda</option>
                                                    <option value="Other" <?php echo !in_array(getCompanySetting('company_country'), ['Kenya', 'Uganda', 'Tanzania', 'Rwanda']) ? 'selected' : ''; ?>>Other</option>
                                                </select>
                                            </div>
                                            
                                            <div class="form-group">
                                                <label for="company_phone" class="form-label">
                                                    <i class="ri-phone-line"></i>Phone Number *
                                                </label>
                                                <input type="tel" class="form-control" id="company_phone" name="company_phone" 
                                                       value="<?php echo htmlspecialchars(getCompanySetting('company_phone', '+254798805300')); ?>" 
                                                       required onchange="updatePreview()">
                                                <div class="form-text">Include country code (e.g., +254 for Kenya)</div>
                                            </div>
                                            
                                            <div class="form-group">
                                                <label for="company_email" class="form-label">
                                                    <i class="ri-mail-send-line"></i>Email Address *
                                                </label>
                                                <input type="email" class="form-control" id="company_email" name="company_email" 
                                                       value="<?php echo htmlspecialchars(getCompanySetting('company_email', 'info@polakis.co.ke')); ?>" 
                                                       required onchange="updatePreview()">
                                                <div class="form-text">Primary business email address</div>
                                            </div>
                                            
                                            <div class="form-group">
                                                <label for="company_website" class="form-label">
                                                    <i class="ri-earth-line"></i>Website URL
                                                </label>
                                                <input type="url" class="form-control" id="company_website" name="company_website" 
                                                       value="<?php echo htmlspecialchars(getCompanySetting('company_website', 'https://www.polakis.co.ke')); ?>" 
                                                       placeholder="https://www.yourcompany.com">
                                                <div class="form-text">Company website URL (optional)</div>
                                            </div>
                                        </div>
                                        
                                        <div class="form-group">
                                            <input type="hidden" name="action" value="update_company">
                                        </div>
                                        
                                        <div class="d-flex justify-content-between align-items-center">
                                            <div class="text-muted">
                                                <i class="ri-information-line me-1"></i>
                                                Fields marked with * are required
                                            </div>
                                            <button type="submit" class="save-button">
                                                <i class="ri-save-line me-2"></i>Save Company Profile
                                            </button>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.js"></script>
    
    <script>
$(document).ready(function() {
    // Company form submission
    $('#companyForm').on('submit', function(e) {
        e.preventDefault();
        saveCompanyProfile();
    });
    
    // Logo upload handling
    $('#logoFileInput').on('change', function() {
        if (this.files && this.files[0]) {
            uploadLogo(this.files[0]);
        }
    });
    
    // Drag and drop functionality
    const uploadArea = document.getElementById('logoUploadArea');
    
    ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
        uploadArea.addEventListener(eventName, preventDefaults, false);
    });
    
    ['dragenter', 'dragover'].forEach(eventName => {
        uploadArea.addEventListener(eventName, highlight, false);
    });
    
    ['dragleave', 'drop'].forEach(eventName => {
        uploadArea.addEventListener(eventName, unhighlight, false);
    });
    
    uploadArea.addEventListener('drop', handleDrop, false);
    
    function preventDefaults(e) {
        e.preventDefault();
        e.stopPropagation();
    }
    
    function highlight() {
        uploadArea.classList.add('dragover');
    }
    
    function unhighlight() {
        uploadArea.classList.remove('dragover');
    }
    
    function handleDrop(e) {
        const files = e.dataTransfer.files;
        if (files.length > 0) {
            uploadLogo(files[0]);
        }
    }
});

function saveCompanyProfile() {
    const formData = new FormData($('#companyForm')[0]);
    
    // Show loading
    Swal.fire({
        title: 'Saving Company Profile...',
        text: 'Please wait while we update your company information.',
        icon: 'info',
        allowOutsideClick: false,
        showConfirmButton: false,
        didOpen: () => {
            Swal.showLoading();
        }
    });
    
    $.ajax({
        url: 'company_settings.php',
        method: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                Swal.fire({
                    title: 'Profile Updated!',
                    text: response.message,
                    icon: 'success',
                    timer: 3000,
                    showConfirmButton: false
                });
            } else {
                Swal.fire({
                    title: 'Error',
                    text: response.message,
                    icon: 'error'
                });
            }
        },
        error: function() {
            Swal.fire({
                title: 'Error',
                text: 'An error occurred while saving the company profile.',
                icon: 'error'
            });
        }
    });
}

function uploadLogo(file) {
    // Validate file
    const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/svg+xml'];
    const maxSize = 2 * 1024 * 1024; // 2MB
    
    if (!allowedTypes.includes(file.type)) {
        Swal.fire({
            title: 'Invalid File Type',
            text: 'Please upload a JPG, PNG, GIF, or SVG image.',
            icon: 'error'
        });
        return;
    }
    
    if (file.size > maxSize) {
        Swal.fire({
            title: 'File Too Large',
            text: 'Please upload an image smaller than 2MB.',
            icon: 'error'
        });
        return;
    }
    
    // Create form data
    const formData = new FormData();
    formData.append('company_logo', file);
    formData.append('action', 'upload_logo');
    
    // Show loading
    Swal.fire({
        title: 'Uploading Logo...',
        text: 'Please wait while we upload your company logo.',
        icon: 'info',
        allowOutsideClick: false,
        showConfirmButton: false,
        didOpen: () => {
            Swal.showLoading();
        }
    });
    
    $.ajax({
        url: 'company_settings.php',
        method: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                // Update UI with new logo
                updateLogoDisplay(response.logo_path);
                
                Swal.fire({
                    title: 'Logo Uploaded!',
                    text: response.message,
                    icon: 'success',
                    timer: 3000,
                    showConfirmButton: false
                });
            } else {
                Swal.fire({
                    title: 'Upload Failed',
                    text: response.message,
                    icon: 'error'
                });
            }
        },
        error: function() {
            Swal.fire({
                title: 'Upload Error',
                text: 'An error occurred while uploading the logo.',
                icon: 'error'
            });
        }
    });
}

function updateLogoDisplay(logoPath) {
    const uploadArea = document.getElementById('logoUploadArea');
    const previewLogo = document.getElementById('previewLogo');
    
    // Update upload area
    uploadArea.innerHTML = `
        <img src="${logoPath}" alt="Current Logo" class="current-logo" id="currentLogo">
        <div class="upload-text">Click to change logo</div>
        <div class="upload-hint">Drag and drop or click to select</div>
        <div class="upload-hint mt-2">Recommended: 300x150px, PNG/JPG format</div>
    `;
    
    // Update preview
    if (previewLogo) {
        previewLogo.src = logoPath;
    } else {
        const previewDiv = document.getElementById('companyPreview');
        const logoImg = document.createElement('img');
        logoImg.src = logoPath;
        logoImg.alt = 'Company Logo';
        logoImg.className = 'preview-logo';
        logoImg.id = 'previewLogo';
        previewDiv.insertBefore(logoImg, previewDiv.firstChild);
    }
}

function updatePreview() {
    const name = document.getElementById('company_name').value || 'Your Company Name';
    const address = document.getElementById('company_address').value || 'Company Address';
    const city = document.getElementById('company_city').value || 'City';
    const country = document.getElementById('company_country').value || 'Country';
    const phone = document.getElementById('company_phone').value || 'Phone Number';
    const email = document.getElementById('company_email').value || 'email@company.com';
    
    document.getElementById('previewName').textContent = name;
    document.getElementById('previewAddress').textContent = address;
    document.getElementById('previewCityCountry').textContent = `${city}, ${country}`;
    document.getElementById('previewPhone').textContent = phone;
    document.getElementById('previewEmail').textContent = email;
}

// Initialize tooltips
$('[title]').tooltip();

// Form validation
$('#companyForm').on('input change', function() {
    const requiredFields = ['company_name', 'company_address', 'company_city', 'company_country', 'company_phone', 'company_email'];
    let isValid = true;
    
    requiredFields.forEach(function(fieldName) {
        const field = document.getElementById(fieldName);
        if (!field.value.trim()) {
            isValid = false;
        }
    });
    
    $('.save-button').prop('disabled', !isValid);
});
</script>

    <!-- App js -->
    <script src="assets/js/app.js"></script>
</body>
</html>