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

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

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

$error = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'update_profile') {
        $name = trim($_POST['name'] ?? '');
        $phone = trim($_POST['phone'] ?? '');
        
        db()->query(
            "UPDATE customers SET name = :name, phone = :phone, updated_at = NOW() WHERE customer_id = :id",
            ['name' => $name, 'phone' => $phone, 'id' => $customer['customer_id']]
        );
        
        $success = 'Profile updated successfully';
        $customer['name'] = $name;
        $customer['phone'] = $phone;
    }
    
    if ($action === 'change_password') {
        $currentPassword = $_POST['current_password'] ?? '';
        $newPassword = $_POST['new_password'] ?? '';
        $confirmPassword = $_POST['confirm_password'] ?? '';
        
        if (!password_verify($currentPassword, $customer['password_hash'])) {
            $error = 'Current password is incorrect';
        } elseif (strlen($newPassword) < 8) {
            $error = 'New password must be at least 8 characters';
        } elseif ($newPassword !== $confirmPassword) {
            $error = 'New passwords do not match';
        } else {
            $newHash = password_hash($newPassword, PASSWORD_DEFAULT);
            db()->query(
                "UPDATE customers SET password_hash = :hash, updated_at = NOW() WHERE customer_id = :id",
                ['hash' => $newHash, 'id' => $customer['customer_id']]
            );
            $success = 'Password changed successfully';
        }
    }
    
    if ($action === 'update_preferences') {
        $newsletter = isset($_POST['newsletter']) ? 1 : 0;
        $smsNotifications = isset($_POST['sms_notifications']) ? 1 : 0;
        
        $preferences = [
            'newsletter' => $newsletter,
            'sms_notifications' => $smsNotifications
        ];
        
        db()->query(
            "UPDATE customers SET preferences = :prefs, updated_at = NOW() WHERE customer_id = :id",
            ['prefs' => json_encode($preferences), 'id' => $customer['customer_id']]
        );
        
        // Update newsletter subscription
        if ($newsletter) {
            $existing = db()->fetch("SELECT id FROM email_subscribers WHERE email = :email", ['email' => $customer['email']]);
            if (!$existing) {
                db()->insert('email_subscribers', [
                    'email' => strtolower($customer['email']),
                    'name' => $customer['name'],
                    'source' => 'account'
                ]);
            }
        } else {
            db()->query("DELETE FROM email_subscribers WHERE email = :email", ['email' => $customer['email']]);
        }
        
        $success = 'Preferences updated';
    }
}

$preferences = json_decode($customer['preferences'] ?? '{}', true);

$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">
    <h1>My Profile</h1>
    <p class="text-muted">Manage your account settings</p>
</div>

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

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

<!-- Profile Information -->
<div class="section-card">
    <div class="section-card-header">
        <h3><i class="fas fa-user"></i> Personal Information</h3>
    </div>
    <div class="section-card-body">
        <form method="POST">
            <input type="hidden" name="action" value="update_profile">
            
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1.5rem;">
                <div class="form-group">
                    <label class="form-label">Full Name</label>
                    <input type="text" name="name" class="form-input" value="<?= htmlspecialchars($customer['name'] ?? '') ?>">
                </div>
                
                <div class="form-group">
                    <label class="form-label">Email Address</label>
                    <input type="email" class="form-input" value="<?= htmlspecialchars($customer['email']) ?>" disabled>
                    <small class="text-muted">Contact support to change your email</small>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Phone Number</label>
                    <input type="tel" name="phone" class="form-input" value="<?= htmlspecialchars($customer['phone'] ?? '') ?>">
                </div>
                
                <div class="form-group">
                    <label class="form-label">Member Since</label>
                    <input type="text" class="form-input" value="<?= formatDate($customer['created_at']) ?>" disabled>
                </div>
            </div>
            
            <button type="submit" class="btn btn-primary mt-1">
                <i class="fas fa-save"></i> Save Changes
            </button>
        </form>
    </div>
</div>

<!-- Change Password -->
<div class="section-card">
    <div class="section-card-header">
        <h3><i class="fas fa-lock"></i> Change Password</h3>
    </div>
    <div class="section-card-body">
        <form method="POST">
            <input type="hidden" name="action" value="change_password">
            
            <div style="display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 1.5rem;">
                <div class="form-group">
                    <label class="form-label">Current Password</label>
                    <input type="password" name="current_password" class="form-input" required>
                </div>
                
                <div class="form-group">
                    <label class="form-label">New Password</label>
                    <input type="password" name="new_password" class="form-input" required minlength="8">
                </div>
                
                <div class="form-group">
                    <label class="form-label">Confirm New Password</label>
                    <input type="password" name="confirm_password" class="form-input" required>
                </div>
            </div>
            
            <button type="submit" class="btn btn-primary">
                <i class="fas fa-key"></i> Change Password
            </button>
        </form>
    </div>
</div>

<!-- Communication Preferences -->
<div class="section-card">
    <div class="section-card-header">
        <h3><i class="fas fa-bell"></i> Communication Preferences</h3>
    </div>
    <div class="section-card-body">
        <form method="POST">
            <input type="hidden" name="action" value="update_preferences">
            
            <div class="form-group">
                <label class="form-checkbox">
                    <input type="checkbox" name="newsletter" <?= !empty($preferences['newsletter']) ? 'checked' : '' ?>>
                    <strong>Email Newsletter</strong>
                    <br><span class="text-muted" style="font-size: 0.875rem; margin-left: 1.5rem;">
                        Receive updates about new products, promotions, and news
                    </span>
                </label>
            </div>
            
            <div class="form-group">
                <label class="form-checkbox">
                    <input type="checkbox" name="sms_notifications" <?= !empty($preferences['sms_notifications']) ? 'checked' : '' ?>>
                    <strong>SMS Notifications</strong>
                    <br><span class="text-muted" style="font-size: 0.875rem; margin-left: 1.5rem;">
                        Receive order updates and alerts via text message
                    </span>
                </label>
            </div>
            
            <button type="submit" class="btn btn-primary">
                <i class="fas fa-save"></i> Save Preferences
            </button>
        </form>
    </div>
</div>

<!-- Delete Account -->
<div class="section-card" style="border: 1px solid var(--color-error);">
    <div class="section-card-header" style="background: rgba(239, 68, 68, 0.1);">
        <h3 style="color: var(--color-error);"><i class="fas fa-exclamation-triangle"></i> Danger Zone</h3>
    </div>
    <div class="section-card-body">
        <p class="text-muted" style="margin-bottom: 1rem;">
            Once you delete your account, there is no going back. Please be certain.
        </p>
        <button class="btn btn-danger" onclick="confirmDeleteAccount()">
            <i class="fas fa-trash"></i> Delete My Account
        </button>
    </div>
</div>

<script>
function confirmDeleteAccount() {
    if (confirm('Are you sure you want to delete your account? This action cannot be undone.')) {
        if (confirm('This will permanently delete all your data including orders, wishlist, and wallet balance. Type your email to confirm.')) {
            const email = prompt('Type your email to confirm deletion:');
            if (email === '<?= addslashes($customer['email']) ?>') {
                window.location.href = '/api/delete-account.php';
            } else {
                alert('Email does not match. Account not deleted.');
            }
        }
    }
}
</script>

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