<?php
/**
 * Tom's Java Jive - Customer Addresses
 */

$pageTitle = "My Addresses - Tom's Java Jive";
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/auth.php';

CustomerAuth::require();
$customer = CustomerAuth::getFullUser();
$currentPage = 'addresses';

// Get addresses from customer record
$addresses = json_decode($customer['addresses'] ?? '[]', true);
if (!is_array($addresses)) $addresses = [];

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'add' || $action === 'edit') {
        $index = isset($_POST['index']) ? intval($_POST['index']) : -1;
        
        $address = [
            'id' => $index >= 0 && isset($addresses[$index]['id']) ? $addresses[$index]['id'] : uniqid('addr_'),
            'name' => trim($_POST['name'] ?? ''),
            'phone' => trim($_POST['phone'] ?? ''),
            'address' => trim($_POST['address'] ?? ''),
            'address2' => trim($_POST['address2'] ?? ''),
            'city' => trim($_POST['city'] ?? ''),
            'state' => trim($_POST['state'] ?? ''),
            'zip' => trim($_POST['zip'] ?? ''),
            'country' => trim($_POST['country'] ?? 'USA'),
            'is_default' => isset($_POST['is_default']),
        ];
        
        // Validate
        if (empty($address['name']) || empty($address['address']) || empty($address['city']) || empty($address['zip'])) {
            setFlash('error', 'Please fill in all required fields');
        } else {
            // Handle default
            if ($address['is_default']) {
                foreach ($addresses as &$a) {
                    $a['is_default'] = false;
                }
            }
            
            if ($index >= 0 && isset($addresses[$index])) {
                $addresses[$index] = $address;
            } else {
                $addresses[] = $address;
            }
            
            // Save
            db()->query(
                "UPDATE customers SET addresses = :addresses WHERE customer_id = :id",
                ['addresses' => json_encode($addresses), 'id' => $customer['customer_id']]
            );
            
            setFlash('success', $action === 'add' ? 'Address added' : 'Address updated');
            redirect('/account/addresses.php');
        }
    }
    
    if ($action === 'delete') {
        $index = intval($_POST['index'] ?? -1);
        if ($index >= 0 && isset($addresses[$index])) {
            array_splice($addresses, $index, 1);
            db()->query(
                "UPDATE customers SET addresses = :addresses WHERE customer_id = :id",
                ['addresses' => json_encode($addresses), 'id' => $customer['customer_id']]
            );
            setFlash('success', 'Address deleted');
        }
        redirect('/account/addresses.php');
    }
    
    if ($action === 'set_default') {
        $index = intval($_POST['index'] ?? -1);
        if ($index >= 0 && isset($addresses[$index])) {
            foreach ($addresses as $i => &$a) {
                $a['is_default'] = ($i === $index);
            }
            db()->query(
                "UPDATE customers SET addresses = :addresses WHERE customer_id = :id",
                ['addresses' => json_encode($addresses), 'id' => $customer['customer_id']]
            );
            setFlash('success', 'Default address updated');
        }
        redirect('/account/addresses.php');
    }
}

$extraHead = '<link rel="stylesheet" href="/assets/css/account.css?v='. filemtime(__DIR__ . '/../assets/css/account.css') .'">';
require_once __DIR__ . '/../includes/header.php';
require_once __DIR__ . '/includes/sidebar.php';
?>

<div class="account-header" style="display: flex; justify-content: space-between; align-items: center;">
    <div>
        <h1>My Addresses</h1>
        <p class="text-muted">Manage your shipping and billing addresses</p>
    </div>
    <button class="btn btn-primary" onclick="openAddressModal()">
        <i class="fas fa-plus"></i> Add Address
    </button>
</div>

<?php if (hasFlash('success')): ?>
    <div class="alert alert-success mb-2">
        <i class="fas fa-check-circle"></i> <?= getFlash('success') ?>
    </div>
<?php endif; ?>

<?php if (hasFlash('error')): ?>
    <div class="alert alert-error mb-2">
        <i class="fas fa-exclamation-circle"></i> <?= getFlash('error') ?>
    </div>
<?php endif; ?>

<?php if (empty($addresses)): ?>
    <div class="section-card">
        <div class="section-card-body text-center" style="padding: 3rem;">
            <i class="fas fa-map-marker-alt" style="font-size: 3rem; color: var(--color-text-muted); margin-bottom: 1rem;"></i>
            <h3>No addresses saved</h3>
            <p class="text-muted">Add an address for faster checkout.</p>
            <button class="btn btn-primary mt-1" onclick="openAddressModal()">
                <i class="fas fa-plus"></i> Add Address
            </button>
        </div>
    </div>
<?php else: ?>
    <div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 1.5rem;">
        <?php foreach ($addresses as $index => $addr): ?>
            <div class="section-card">
                <div class="section-card-body">
                    <?php if (!empty($addr['is_default'])): ?>
                        <span class="badge badge-primary" style="margin-bottom: 0.75rem;">Default</span>
                    <?php endif; ?>
                    
                    <h4 style="margin: 0 0 0.5rem;"><?= htmlspecialchars($addr['name']) ?></h4>
                    
                    <p style="margin: 0 0 0.25rem;"><?= htmlspecialchars($addr['address']) ?></p>
                    <?php if (!empty($addr['address2'])): ?>
                        <p style="margin: 0 0 0.25rem;"><?= htmlspecialchars($addr['address2']) ?></p>
                    <?php endif; ?>
                    <p style="margin: 0 0 0.25rem;">
                        <?= htmlspecialchars($addr['city']) ?>, <?= htmlspecialchars($addr['state']) ?> <?= htmlspecialchars($addr['zip']) ?>
                    </p>
                    <p style="margin: 0 0 0.75rem;"><?= htmlspecialchars($addr['country'] ?? 'USA') ?></p>
                    
                    <?php if (!empty($addr['phone'])): ?>
                        <p class="text-muted" style="margin: 0 0 1rem;">
                            <i class="fas fa-phone"></i> <?= htmlspecialchars($addr['phone']) ?>
                        </p>
                    <?php endif; ?>
                    
                    <div style="display: flex; gap: 0.5rem; flex-wrap: wrap;">
                        <button class="btn btn-sm btn-secondary" onclick="editAddress(<?= $index ?>)">
                            <i class="fas fa-edit"></i> Edit
                        </button>
                        
                        <?php if (empty($addr['is_default'])): ?>
                            <form method="POST" style="display: inline;">
                                <input type="hidden" name="action" value="set_default">
                                <input type="hidden" name="index" value="<?= $index ?>">
                                <button type="submit" class="btn btn-sm btn-secondary">
                                    <i class="fas fa-check"></i> Make Default
                                </button>
                            </form>
                        <?php endif; ?>
                        
                        <form method="POST" style="display: inline;" onsubmit="return confirm('Delete this address?')">
                            <input type="hidden" name="action" value="delete">
                            <input type="hidden" name="index" value="<?= $index ?>">
                            <button type="submit" class="btn btn-sm btn-danger">
                                <i class="fas fa-trash"></i>
                            </button>
                        </form>
                    </div>
                </div>
            </div>
        <?php endforeach; ?>
    </div>
<?php endif; ?>

<!-- Address Modal -->
<div class="modal-overlay" id="addressModal">
    <div class="modal">
        <div class="modal-header">
            <h3 class="modal-title" id="addressModalTitle">Add Address</h3>
            <button type="button" class="modal-close" onclick="Modal.close('addressModal')">&times;</button>
        </div>
        <form method="POST" id="addressForm">
            <input type="hidden" name="action" id="addressAction" value="add">
            <input type="hidden" name="index" id="addressIndex" value="-1">
            <div class="modal-body">
                <div class="form-group">
                    <label class="form-label">Full Name *</label>
                    <input type="text" name="name" id="addr_name" class="form-input" required>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Phone Number</label>
                    <input type="tel" name="phone" id="addr_phone" class="form-input">
                </div>
                
                <div class="form-group">
                    <label class="form-label">Street Address *</label>
                    <input type="text" name="address" id="addr_address" class="form-input" required>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Apartment, suite, etc.</label>
                    <input type="text" name="address2" id="addr_address2" class="form-input">
                </div>
                
                <div style="display: grid; grid-template-columns: 2fr 1fr 1fr; gap: 1rem;">
                    <div class="form-group">
                        <label class="form-label">City *</label>
                        <input type="text" name="city" id="addr_city" class="form-input" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">State *</label>
                        <input type="text" name="state" id="addr_state" class="form-input" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">ZIP *</label>
                        <input type="text" name="zip" id="addr_zip" class="form-input" required>
                    </div>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Country</label>
                    <select name="country" id="addr_country" class="form-select">
                        <option value="USA">United States</option>
                        <option value="Canada">Canada</option>
                    </select>
                </div>
                
                <div class="form-group">
                    <label class="form-checkbox">
                        <input type="checkbox" name="is_default" id="addr_default">
                        Set as default address
                    </label>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="Modal.close('addressModal')">Cancel</button>
                <button type="submit" class="btn btn-primary">Save Address</button>
            </div>
        </form>
    </div>
</div>

<script>
const addresses = <?= json_encode($addresses) ?>;

function openAddressModal() {
    document.getElementById('addressModalTitle').textContent = 'Add Address';
    document.getElementById('addressAction').value = 'add';
    document.getElementById('addressIndex').value = '-1';
    document.getElementById('addressForm').reset();
    Modal.open('addressModal');
}

function editAddress(index) {
    const addr = addresses[index];
    if (!addr) return;
    
    document.getElementById('addressModalTitle').textContent = 'Edit Address';
    document.getElementById('addressAction').value = 'edit';
    document.getElementById('addressIndex').value = index;
    
    document.getElementById('addr_name').value = addr.name || '';
    document.getElementById('addr_phone').value = addr.phone || '';
    document.getElementById('addr_address').value = addr.address || '';
    document.getElementById('addr_address2').value = addr.address2 || '';
    document.getElementById('addr_city').value = addr.city || '';
    document.getElementById('addr_state').value = addr.state || '';
    document.getElementById('addr_zip').value = addr.zip || '';
    document.getElementById('addr_country').value = addr.country || 'USA';
    document.getElementById('addr_default').checked = !!addr.is_default;
    
    Modal.open('addressModal');
}
</script>

<?php require_once __DIR__ . '/includes/footer.php'; ?>
