<style>
.form-header-modern {
    background: linear-gradient(135deg, #72A565 0%, #91A134 100%);
    color: white;
    padding: 2rem;
    border-radius: 15px;
    margin-bottom: 2rem;
    box-shadow: 0 10px 30px rgba(114, 165, 101, 0.2);
}

.form-card-modern {
    background: white;
    border-radius: 15px;
    box-shadow: 0 5px 15px rgba(0,0,0,0.08);
    margin-bottom: 1.5rem;
    border: none;
    overflow: hidden;
}

.form-card-modern .card-header {
    background: linear-gradient(135deg, #f7fafc 0%, #edf2f7 100%);
    border-bottom: 2px solid #e2e8f0;
    padding: 1.25rem 1.5rem;
    font-weight: 600;
    color: #2d3748;
}

.form-card-modern .card-body {
    padding: 2rem;
}

.form-label-modern {
    font-weight: 600;
    color: #2d3748;
    margin-bottom: 0.5rem;
    font-size: 0.875rem;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.form-control-modern {
    border-radius: 10px;
    border: 2px solid #e2e8f0;
    padding: 0.75rem 1rem;
    transition: all 0.3s ease;
    font-size: 1rem;
}

.form-control-modern:focus {
    border-color: #72A565;
    box-shadow: 0 0 0 3px rgba(114, 165, 101, 0.1);
    outline: none;
}

.btn-submit-modern {
    background: linear-gradient(135deg, #72A565 0%, #91A134 100%);
    border: none;
    color: white;
    padding: 0.75rem 2rem;
    border-radius: 10px;
    font-weight: 600;
    transition: all 0.3s ease;
    box-shadow: 0 4px 6px rgba(114, 165, 101, 0.3);
}

.btn-submit-modern:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 12px rgba(114, 165, 101, 0.4);
    color: white;
}

.form-group-modern {
    margin-bottom: 1.5rem;
}

.info-box {
    background: #f7fafc;
    border-left: 4px solid #72A565;
    padding: 1rem;
    border-radius: 8px;
    margin-bottom: 1.5rem;
}

.info-box i {
    color: #72A565;
    margin-right: 0.5rem;
}

.image-preview {
    width: 120px;
    height: 120px;
    object-fit: cover;
    border-radius: 10px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    margin-top: 0.5rem;
}

.id-preview {
    width: 100px;
    height: 100px;
    object-fit: cover;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    margin-top: 0.5rem;
}

.form-check-input:checked {
    background-color: #72A565;
    border-color: #72A565;
}

.file-upload-wrapper {
    position: relative;
    display: inline-block;
    width: 100%;
}

.file-upload-label {
    display: block;
    padding: 0.75rem 1rem;
    background: #f7fafc;
    border: 2px dashed #e2e8f0;
    border-radius: 10px;
    text-align: center;
    cursor: pointer;
    transition: all 0.3s ease;
}

.file-upload-label:hover {
    background: #edf2f7;
    border-color: #72A565;
}

.file-upload-input {
    position: absolute;
    opacity: 0;
    width: 100%;
    height: 100%;
    cursor: pointer;
}
</style>

<!-- Header Section -->
<div class="form-header-modern">
    <div class="d-flex justify-content-between align-items-center">
        <div>
            <h2 class="mb-2">
                <i class="fa-solid fa-<?php echo (isset($customer)) ? 'edit' : 'user-plus'; ?>"></i> 
                <?php echo (isset($customer)) ? 'Edit Customer' : 'Add New Customer'; ?>
            </h2>
            <p class="mb-0 opacity-75"><?php echo (isset($customer)) ? 'Update customer information' : 'Create a new customer account'; ?></p>
        </div>
        <div>
            <a href="<?php echo base_url('customer'); ?>" class="btn btn-light btn-modern">
                <i class="fa-solid fa-arrow-left"></i> Back to Customers
            </a>
        </div>
    </div>
</div>

<?php
$customer = isset($customerdetails) ? $customerdetails : null;
$endpoint = isset($customer) ? 'updatecustomerdata/' . $id : 'insertcustomer';
?>

<form method="post" id="customerForm" action="<?php echo base_url('customer/' . $endpoint); ?>" enctype="multipart/form-data">
    <?php if (isset($id)): ?>
        <input type="hidden" name="id" value="<?php echo $id; ?>">
    <?php endif; ?>
    
    <!-- Basic Information -->
    <div class="form-card-modern">
        <div class="card-header">
            <h5 class="mb-0">
                <i class="fa-solid fa-user text-primary"></i> Basic Information
            </h5>
        </div>
        <div class="card-body">
            <div class="row">
                <div class="col-md-6 form-group-modern">
                    <label class="form-label-modern">First Name <span class="text-danger">*</span></label>
                    <input type="text" 
                        class="form-control form-control-modern" 
                        name="firstName" 
                        value="<?php echo isset($customer['firstName']) ? htmlspecialchars($customer['firstName']) : ''; ?>" 
                        placeholder="Enter first name" 
                        required>
                </div>
                <div class="col-md-6 form-group-modern">
                    <label class="form-label-modern">Last Name</label>
                    <input type="text" 
                        class="form-control form-control-modern" 
                        name="lastName" 
                        value="<?php echo isset($customer['lastName']) ? htmlspecialchars($customer['lastName']) : ''; ?>" 
                        placeholder="Enter last name">
                </div>
            </div>
            
            <div class="row">
                <div class="col-md-6 form-group-modern">
                    <label class="form-label-modern">Email <span class="text-danger">*</span></label>
                    <input type="email" 
                        class="form-control form-control-modern" 
                        name="email" 
                        value="<?php echo isset($customer['email']) ? htmlspecialchars($customer['email']) : ''; ?>" 
                        placeholder="Enter email address" 
                        <?php echo isset($customer) ? 'readonly' : 'required'; ?>>
                    <?php if (isset($customer)): ?>
                        <small class="text-muted">Email cannot be changed after creation</small>
                    <?php endif; ?>
                </div>
                <div class="col-md-6 form-group-modern">
                    <label class="form-label-modern">Phone Number</label>
                    <input type="text" 
                        class="form-control form-control-modern" 
                        name="phoneNumber" 
                        value="<?php echo isset($customer['phoneNumber']) ? htmlspecialchars($customer['phoneNumber']) : ''; ?>" 
                        placeholder="Enter phone number">
                </div>
            </div>
        </div>
    </div>

    <!-- Account Settings -->
    <div class="form-card-modern">
        <div class="card-header">
            <h5 class="mb-0">
                <i class="fa-solid fa-key text-primary"></i> Account Settings
            </h5>
        </div>
        <div class="card-body">
            <div class="row">
                <div class="col-md-6 form-group-modern">
                    <label class="form-label-modern">
                        <?php echo isset($customer) ? 'New Password' : 'Password'; ?> 
                        <?php if (!isset($customer)): ?><span class="text-danger">*</span><?php endif; ?>
                    </label>
                    <input type="password" 
                        class="form-control form-control-modern" 
                        name="<?php echo isset($customer) ? 'newpassword' : 'password'; ?>" 
                        placeholder="<?php echo isset($customer) ? 'Leave blank to keep current password' : 'Enter password'; ?>" 
                        <?php echo isset($customer) ? '' : 'required'; ?>
                        minlength="6">
                    <?php if (isset($customer)): ?>
                        <small class="text-muted">Leave blank to keep current password. Minimum 6 characters.</small>
                    <?php else: ?>
                        <small class="text-muted">Minimum 6 characters</small>
                    <?php endif; ?>
                </div>
                <div class="col-md-6 form-group-modern">
                    <label class="form-label-modern">City Assignment</label>
                    <select class="form-control form-control-modern" name="cityId">
                        <option value="">Select City (Optional)</option>
                        <?php if (isset($cities) && !empty($cities)): 
                            foreach ($cities as $cityId => $city): 
                                $cityName = isset($city['cityName']) ? $city['cityName'] : $cityId;
                                $selected = (isset($customer['cityId']) && $customer['cityId'] == $cityId) ? 'selected' : '';
                        ?>
                            <option value="<?php echo htmlspecialchars($cityId); ?>" <?php echo $selected; ?>>
                                <?php echo htmlspecialchars($cityName); ?>
                            </option>
                        <?php endforeach; endif; ?>
                    </select>
                    <small class="text-muted">Assign customer to a specific market/city</small>
                </div>
            </div>
            
            <div class="row">
                <div class="col-md-6 form-group-modern">
                    <label class="form-label-modern">Loyalty Points</label>
                    <input type="number" 
                        class="form-control form-control-modern" 
                        name="points" 
                        value="<?php echo isset($customer['points']) ? intval($customer['points']) : 0; ?>" 
                        placeholder="0" 
                        min="0">
                    <small class="text-muted">Initial loyalty points for the customer</small>
                </div>
                <div class="col-md-6 form-group-modern">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-check form-switch mt-4">
                                <input class="form-check-input" type="checkbox" name="isApproved" id="isApproved" 
                                    <?php echo (!isset($customer) || (isset($customer['isApproved']) && $customer['isApproved'])) ? 'checked' : ''; ?>>
                                <label class="form-check-label" for="isApproved">
                                    <strong>Approved</strong>
                                </label>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-check form-switch mt-4">
                                <input class="form-check-input" type="checkbox" name="isActive" id="isActive" 
                                    <?php echo (!isset($customer) || (isset($customer['isActive']) && $customer['isActive'])) ? 'checked' : ''; ?>>
                                <label class="form-check-label" for="isActive">
                                    <strong>Active</strong>
                                </label>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Profile Image -->
    <div class="form-card-modern">
        <div class="card-header">
            <h5 class="mb-0">
                <i class="fa-solid fa-image text-primary"></i> Profile Image
            </h5>
        </div>
        <div class="card-body">
            <div class="row">
                <div class="col-md-6 form-group-modern">
                    <label class="form-label-modern">Profile Picture</label>
                    <div class="file-upload-wrapper">
                        <label class="file-upload-label" for="profile_image">
                            <i class="fa-solid fa-cloud-upload-alt fa-2x mb-2"></i>
                            <div>Click to upload or drag and drop</div>
                            <small class="text-muted">PNG, JPG up to 5MB</small>
                        </label>
                        <input type="file" 
                            class="file-upload-input" 
                            id="profile_image" 
                            name="profile_image" 
                            accept="image/*"
                            onchange="previewImage(this, 'profilePreview')">
                    </div>
                    <?php if (isset($customer['image']) && $customer['image'] != ''): ?>
                        <img src="<?php echo htmlspecialchars($customer['image']); ?>" 
                             class="image-preview" 
                             id="profilePreview" 
                             alt="Profile">
                    <?php else: ?>
                        <img src="" class="image-preview" id="profilePreview" alt="Profile" style="display: none;">
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <!-- ID Verification -->
    <div class="form-card-modern">
        <div class="card-header">
            <h5 class="mb-0">
                <i class="fa-solid fa-id-card text-primary"></i> ID Verification (Optional)
            </h5>
        </div>
        <div class="card-body">
            <div class="info-box">
                <i class="fa-solid fa-info-circle"></i>
                <strong>Note:</strong> Upload front and back images of customer's ID for verification purposes.
            </div>
            
            <div class="row">
                <div class="col-md-6 form-group-modern">
                    <label class="form-label-modern">ID Front Image</label>
                    <div class="file-upload-wrapper">
                        <label class="file-upload-label" for="idFront">
                            <i class="fa-solid fa-id-card fa-2x mb-2"></i>
                            <div>Upload Front ID</div>
                            <small class="text-muted">PNG, JPG up to 5MB</small>
                        </label>
                        <input type="file" 
                            class="file-upload-input" 
                            id="idFront" 
                            name="idFront" 
                            accept="image/*"
                            onchange="previewImage(this, 'idFrontPreview')">
                    </div>
                    <?php if (isset($customer['idFront']) && $customer['idFront'] != ''): ?>
                        <img src="<?php echo htmlspecialchars($customer['idFront']); ?>" 
                             class="id-preview" 
                             id="idFrontPreview" 
                             alt="ID Front">
                    <?php else: ?>
                        <img src="" class="id-preview" id="idFrontPreview" alt="ID Front" style="display: none;">
                    <?php endif; ?>
                </div>
                
                <div class="col-md-6 form-group-modern">
                    <label class="form-label-modern">ID Back Image</label>
                    <div class="file-upload-wrapper">
                        <label class="file-upload-label" for="idBack">
                            <i class="fa-solid fa-id-card fa-2x mb-2"></i>
                            <div>Upload Back ID</div>
                            <small class="text-muted">PNG, JPG up to 5MB</small>
                        </label>
                        <input type="file" 
                            class="file-upload-input" 
                            id="idBack" 
                            name="idBack" 
                            accept="image/*"
                            onchange="previewImage(this, 'idBackPreview')">
                    </div>
                    <?php if (isset($customer['idBack']) && $customer['idBack'] != ''): ?>
                        <img src="<?php echo htmlspecialchars($customer['idBack']); ?>" 
                             class="id-preview" 
                             id="idBackPreview" 
                             alt="ID Back">
                    <?php else: ?>
                        <img src="" class="id-preview" id="idBackPreview" alt="ID Back" style="display: none;">
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <!-- Submit Button -->
    <div class="text-end mb-4">
        <a href="<?php echo base_url('customer'); ?>" class="btn btn-secondary btn-modern me-2">
            <i class="fa-solid fa-times"></i> Cancel
        </a>
        <button type="submit" class="btn btn-submit-modern">
            <i class="fa-solid fa-<?php echo isset($customer) ? 'save' : 'plus'; ?>"></i> 
            <?php echo isset($customer) ? 'Update Customer' : 'Add Customer'; ?>
        </button>
    </div>
</form>

<!-- SweetAlert2 -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script src="<?php echo base_url('assets/js/jquery.min.js'); ?>"></script>
<script>
function previewImage(input, previewId) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function(e) {
            $('#' + previewId).attr('src', e.target.result).show();
        };
        reader.readAsDataURL(input.files[0]);
    }
}

$(document).ready(function() {
    // Form submission
    $('#customerForm').on('submit', function(e) {
        e.preventDefault();
        
        var form = $(this);
        var formData = new FormData(form[0]);
        var url = form.attr('action');
        var isEdit = <?php echo isset($customer) ? 'true' : 'false'; ?>;
        
        var submitBtn = form.find('button[type="submit"]');
        var originalText = submitBtn.html();
        submitBtn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Processing...');
        
        $.ajax({
            url: url,
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            dataType: 'json',
            success: function(response) {
                submitBtn.prop('disabled', false).html(originalText);
                
                if (response.success) {
                    Swal.fire({
                        icon: 'success',
                        title: 'Success!',
                        text: response.message,
                        confirmButtonText: 'OK',
                        timer: 2000,
                        timerProgressBar: true
                    }).then(function() {
                        window.location.href = '<?php echo base_url("customer"); ?>';
                    });
                } else {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error!',
                        text: response.message,
                        confirmButtonText: 'OK'
                    });
                }
            },
            error: function(xhr, status, error) {
                submitBtn.prop('disabled', false).html(originalText);
                
                var errorMessage = 'Something went wrong. Please try again.';
                try {
                    var response = JSON.parse(xhr.responseText);
                    if (response.message) {
                        errorMessage = response.message;
                    }
                } catch (e) {
                    // If not JSON, use default message
                }
                
                Swal.fire({
                    icon: 'error',
                    title: 'Error!',
                    text: errorMessage,
                    confirmButtonText: 'OK'
                });
            }
        });
    });
});
</script>
