<?php
require_once 'config.php';
require_once 'includes/auth.php';
require_once 'includes/order.php';

$pageTitle = 'My Account';
$auth = new Auth();
$orderModel = new Order();

// Check if user is logged in
if (!isLoggedIn()) {
    header('Location: login.php');
    exit;
}

$user = $auth->getUser($_SESSION['user_id']);
$orders = $orderModel->getByUser($_SESSION['user_id']);

$activeTab = isset($_GET['tab']) ? $_GET['tab'] : 'orders';

// Handle profile update
$message = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if ($_POST['action'] === 'update_profile') {
        $fullName = sanitize($_POST['full_name']);
        $phone = sanitize($_POST['phone']);
        $address = sanitize($_POST['address']);
        
        $result = $auth->updateProfile($_SESSION['user_id'], $fullName, $phone, $address);
        $message = $result['message'];
        
        // Refresh user data
        $user = $auth->getUser($_SESSION['user_id']);
    } elseif ($_POST['action'] === 'change_password') {
        $currentPassword = $_POST['current_password'];
        $newPassword = $_POST['new_password'];
        $confirmPassword = $_POST['confirm_password'];
        
        if ($newPassword !== $confirmPassword) {
            $message = 'Passwords do not match.';
        } else {
            $result = $auth->changePassword($_SESSION['user_id'], $currentPassword, $newPassword);
            $message = $result['message'];
        }
    }
}

require_once 'includes/header.php';
?>

<!-- Account Page -->
<section class="account-page">
    <div class="container">
        <h1 class="section-title" style="margin-bottom: var(--spacing-xl);">My Account</h1>
        
        <div class="account-grid">
            <!-- Account Sidebar -->
            <aside class="account-nav">
                <a href="?tab=orders" class="<?php echo $activeTab === 'orders' ? 'active' : ''; ?>">Order History</a>
                <a href="?tab=profile" class="<?php echo $activeTab === 'profile' ? 'active' : ''; ?>">Profile Settings</a>
                <a href="?tab=password" class="<?php echo $activeTab === 'password' ? 'active' : ''; ?>">Change Password</a>
                <a href="<?php echo SITE_URL; ?>/logout.php" style="color: var(--danger);">Logout</a>
            </aside>
            
            <!-- Account Content -->
            <div class="account-content">
                <?php if ($message): ?>
                    <div class="alert alert-success"><?php echo htmlspecialchars($message); ?></div>
                <?php endif; ?>
                
                <?php if ($activeTab === 'orders'): ?>
                    <h2 style="margin-bottom: var(--spacing-lg);">Order History</h2>
                    
                    <?php if (empty($orders)): ?>
                        <p style="color: var(--medium-gray);">You haven't placed any orders yet.</p>
                        <a href="<?php echo SITE_URL; ?>/products.php" class="btn btn-primary" style="margin-top: var(--spacing-md);">Start Shopping</a>
                    <?php else: ?>
                        <?php foreach ($orders as $order): ?>
                            <div class="order-history-item">
                                <div class="order-history-header">
                                    <div>
                                        <strong>Order #<?php echo htmlspecialchars($order['order_number']); ?></strong>
                                        <span class="status-badge status-<?php echo $order['status']; ?>" style="margin-left: var(--spacing-sm);"><?php echo htmlspecialchars($order['status']); ?></span>
                                    </div>
                                    <div><?php echo formatPrice($order['total_amount']); ?></div>
                                </div>
                                <div style="color: var(--medium-gray); font-size: 0.875rem; margin-top: var(--spacing-sm);">
                                    <p>Date: <?php echo date('F j, Y', strtotime($order['created_at'])); ?></p>
                                    <p>Items: <?php echo intval($order['item_count'] ?? 0); ?></p>
                                    <p>Status: <?php echo htmlspecialchars($order['status']); ?></p>
                                </div>
                                <a href="<?php echo SITE_URL; ?>/order.php?id=<?php echo $order['id']; ?>" class="btn btn-small" style="margin-top: var(--spacing-md);">View Details</a>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                    
                <?php elseif ($activeTab === 'profile'): ?>
                    <h2 style="margin-bottom: var(--spacing-lg);">Profile Settings</h2>
                    
                    <form method="POST">
                        <input type="hidden" name="action" value="update_profile">
                        
                        <div class="form-group">
                            <label for="full_name">Full Name</label>
                            <input type="text" id="full_name" name="full_name" value="<?php echo htmlspecialchars($user['full_name']); ?>" required>
                        </div>
                        
                        <div class="form-group">
                            <label for="email">Email</label>
                            <input type="email" id="email" value="<?php echo htmlspecialchars($user['email']); ?>" disabled>
                            <small style="color: var(--medium-gray);">Email cannot be changed.</small>
                        </div>
                        
                        <div class="form-group">
                            <label for="phone">Phone</label>
                            <input type="tel" id="phone" name="phone" value="<?php echo htmlspecialchars($user['phone'] ?? ''); ?>">
                        </div>
                        
                        <div class="form-group">
                            <label for="address">Address</label>
                            <textarea id="address" name="address" rows="3"><?php echo htmlspecialchars($user['address'] ?? ''); ?></textarea>
                        </div>
                        
                        <button type="submit" class="btn btn-primary">Save Changes</button>
                    </form>
                    
                <?php elseif ($activeTab === 'password'): ?>
                    <h2 style="margin-bottom: var(--spacing-lg);">Change Password</h2>
                    
                    <form method="POST">
                        <input type="hidden" name="action" value="change_password">
                        
                        <div class="form-group">
                            <label for="current_password">Current Password</label>
                            <input type="password" id="current_password" name="current_password" required>
                        </div>
                        
                        <div class="form-group">
                            <label for="new_password">New Password</label>
                            <input type="password" id="new_password" name="new_password" required minlength="6">
                        </div>
                        
                        <div class="form-group">
                            <label for="confirm_password">Confirm New Password</label>
                            <input type="password" id="confirm_password" name="confirm_password" required>
                        </div>
                        
                        <button type="submit" class="btn btn-primary">Change Password</button>
                    </form>
                <?php endif; ?>
            </div>
        </div>
    </div>
</section>

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