<?php require KAVEHBOARD_PATH . 'template-part/header.php'; ?>
<?php
/**
 * Edit Address Template
 * Custom template for editing billing and shipping addresses
 */

// Security check
if (!defined('ABSPATH')) {
    exit;
}

// Get address type from URL parameter
$address_type = isset($_GET['type']) ? sanitize_title($_GET['type']) : 'billing';
if (!in_array($address_type, array('billing', 'shipping'))) {
    $address_type = 'billing';
}

$current_user = wp_get_current_user();
$user_id = get_current_user_id();

// Get customer data
$customer = WC()->customer;
$address = array();

if ($address_type === 'billing') {
    $address = $customer->get_billing();
} else {
    $address = $customer->get_shipping();
}

// Handle form submission
$success_message = '';
$error_message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_address'])) {
    if (wp_verify_nonce($_POST['address_nonce'], 'save_address_action')) {
        $address_fields = WC()->countries->get_address_fields(WC()->customer->get_billing_country(), $address_type . '_');
        
        $address_data = array();
        foreach ($address_fields as $key => $field) {
            $field_key = str_replace($address_type . '_', '', $key);
            if (isset($_POST[$key])) {
                $address_data[$field_key] = sanitize_text_field($_POST[$key]);
            }
        }
        
        // Update customer address
        if ($address_type === 'billing') {
            foreach ($address_data as $key => $value) {
                $customer->{'set_billing_' . $key}($value);
            }
        } else {
            foreach ($address_data as $key => $value) {
                $customer->{'set_shipping_' . $key}($value);
            }
        }
        
        $customer->save();
        $success_message = __('Your address has been successfully updated.', 'kavehTheme');
        
        // Refresh address data
        if ($address_type === 'billing') {
            $address = $customer->get_billing();
        } else {
            $address = $customer->get_shipping();
        }
    } else {
        $error_message = __('Form validation error.', 'kavehTheme');
    }
}

// Get address fields
$address_fields = WC()->countries->get_address_fields(WC()->customer->get_billing_country(), $address_type . '_');
?>

<!-- Start Content -->
<div class="dashboard-kaveh-content">

        
    <?php if (!empty($success_message)): ?>
    <div class="col-12">
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <?php echo esc_html($success_message); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    </div>
    <?php endif; ?>
    
    <?php if (!empty($error_message)): ?>
    <div class="col-12">
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <?php echo esc_html($error_message); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    </div>
    <?php endif; ?>
    
    <div class="dashboard-kaveh-profile">
        <!-- Start Heading -->
        <div class="dashboard-kaveh-profile-heading d-flex align-items-md-center flex-column flex-md-row">
            <div class="title d-flex align-items-center flex-fill flex-grow-0 flex-shrink-0">
                <i class="icon-location lh-1 position-relative"></i>
                <?php echo $address_type === 'billing' ? __('Billing Address', 'kavehTheme') : __('Shipping Address', 'kavehTheme'); ?>
            </div>
        </div>
        <!-- End Heading -->
        
        <!-- Start Address Type Tabs -->
        <div class="dashboard-kaveh-address-tabs mb-4">
            <div class="btn-group" role="group">
                <a href="<?php echo add_query_arg('type', 'billing', get_permalink() . 'woo-edit-address/'); ?>" 
                   class="btn <?php echo $address_type === 'billing' ? 'btn-primary' : 'btn-outline-primary'; ?>">
                    <?php _e('Billing Address', 'kavehTheme'); ?>
                </a>
                <a href="<?php echo add_query_arg('type', 'shipping', get_permalink() . 'woo-edit-address/'); ?>" 
                   class="btn <?php echo $address_type === 'shipping' ? 'btn-primary' : 'btn-outline-primary'; ?>">
                    <?php _e('Shipping Address', 'kavehTheme'); ?>
                </a>
            </div>
        </div>
        <!-- End Address Type Tabs -->
        
        <div class="dashboard-kaveh-profile-row d-flex flex-wrap">
            <!-- Start Form -->
            <div class="dashboard-kaveh-profile-row-left w-100 flex-fill flex-grow-0 flex-shrink-0">
                <div class="dashboard-kaveh-profile-form">
                    <form method="post" action="">
                        <?php wp_nonce_field('save_address_action', 'address_nonce'); ?>
                        <div class="row">
                            <?php foreach ($address_fields as $key => $field): ?>
                                <?php 
                                $field_key = str_replace($address_type . '_', '', $key);
                                $field_value = isset($address[$field_key]) ? $address[$field_key] : '';
                                $field_id = esc_attr($key);
                                $field_name = esc_attr($key);
                                $field_label = isset($field['label']) ? $field['label'] : '';
                                $field_required = isset($field['required']) && $field['required'];
                                $field_type = isset($field['type']) ? $field['type'] : 'text';
                                ?>
                                
                                <div class="col-sm-6">
                                    <div class="position-relative">
                                        <label for="<?php echo $field_id; ?>" class="d-inline-block fw-bold">
                                            <?php echo esc_html($field_label); ?>
                                            <?php if ($field_required): ?>
                                                <span class="text-danger">*</span>
                                            <?php endif; ?>
                                        </label>
                                        
                                        <?php if ($field_type === 'select'): ?>
                                            <select name="<?php echo $field_name; ?>" id="<?php echo $field_id; ?>" 
                                                    class="form-control" <?php echo $field_required ? 'required' : ''; ?>>
                                                <?php if (isset($field['options'])): ?>
                                                    <?php foreach ($field['options'] as $option_key => $option_value): ?>
                                                        <option value="<?php echo esc_attr($option_key); ?>" 
                                                                <?php selected($field_value, $option_key); ?>>
                                                            <?php echo esc_html($option_value); ?>
                                                        </option>
                                                    <?php endforeach; ?>
                                                <?php endif; ?>
                                            </select>
                                        <?php elseif ($field_type === 'textarea'): ?>
                                            <textarea name="<?php echo $field_name; ?>" id="<?php echo $field_id; ?>" 
                                                      class="form-control" rows="3" 
                                                      <?php echo $field_required ? 'required' : ''; ?>><?php echo esc_textarea($field_value); ?></textarea>
                                        <?php else: ?>
                                            <input type="<?php echo esc_attr($field_type); ?>" 
                                                   name="<?php echo $field_name; ?>" 
                                                   id="<?php echo $field_id; ?>" 
                                                   class="form-control" 
                                                   value="<?php echo esc_attr($field_value); ?>"
                                                   <?php echo $field_required ? 'required' : ''; ?>>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                        
                        <div class="dashboard-kaveh-profile-form-submit d-flex align-items-center justify-content-between flex-wrap">
                            <button type="submit" name="save_address" class="btn btn-primary fw-bold">
                                <?php _e('Save Changes', 'kavehTheme'); ?>
                            </button>
                        </div>
                    </form>
                </div>
            </div>
            <!-- End Form -->
        </div>
    </div>
</div>
<!-- End Content -->
<?php require KAVEHBOARD_PATH . 'template-part/footer.php'; ?>