<?php
require_once 'functions.php';
requireAuth();

$user = getCurrentUser();
$db = getDB();

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['update_profile'])) {
        $firstName = trim($_POST['first_name'] ?? '');
        $lastName = trim($_POST['last_name'] ?? '');
        $phone = trim($_POST['phone'] ?? '');
        $address = trim($_POST['address'] ?? '');
        $city = trim($_POST['city'] ?? '');
        $state = trim($_POST['state'] ?? '');
        $country = trim($_POST['country'] ?? '');
        $zipCode = trim($_POST['zip_code'] ?? '');
        $occupation = trim($_POST['occupation'] ?? '');
        // Corrected SQL and binding
$stmt = $db->prepare("UPDATE users 
                      SET first_name = ?, 
                          last_name = ?, 
                          phone = ?, 
                          address = ?, 
                          city = ?, 
                          state = ?, 
                          country = ?, 
                          postal_code = ?, 
                          occupation = ? 
                      WHERE id = ?");

// Ensure 9 strings are bound for the fields, plus 1 integer for the ID
$stmt->bind_param('sssssssssi', $firstName, $lastName, $phone, $address, $city, $state, $country, $zipCode, $occupation, $user['id']);
        
        if ($stmt->execute()) {
            $success = 'Profile updated successfully!';
            $user = getCurrentUser();
        } else {
            $error = 'Failed to update profile.';
        }
    }
    
    if (isset($_POST['change_password'])) {
        $currentPassword = $_POST['current_password'] ?? '';
        $newPassword = $_POST['new_password'] ?? '';
        $confirmPassword = $_POST['confirm_password'] ?? '';
        
        if (!verifyPassword($currentPassword, $user['password'])) {
            $error = 'Current password is incorrect.';
        } elseif (strlen($newPassword) < 6) {
            $error = 'New password must be at least 6 characters.';
        } elseif ($newPassword !== $confirmPassword) {
            $error = 'Passwords do not match.';
        } else {
            $hashed = hashPassword($newPassword);
            $stmt = $db->prepare("UPDATE users SET password = ? WHERE id = ?");
            $stmt->bind_param('si', $hashed, $user['id']);
            if ($stmt->execute()) {
                $success = 'Password changed successfully!';
            } else {
                $error = 'Failed to change password.';
            }
        }
    }
}

$flash = getFlash();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Profile - <?php echo SITE_NAME; ?></title>
    <link rel="stylesheet" href="assets/css/style.css">
</head>
<body>
    <?php include 'includes/client-sidebar.php'; ?>
    
    <div class="main-content">
        <?php include 'includes/client-header.php'; ?>
        
        <div class="page-content">
            <?php if ($flash): ?>
                <div class="alert alert-<?php echo $flash['type']; ?> fade-in">
                    <span><?php echo $flash['type'] === 'success' ? '✓' : '⚠'; ?></span> <?php echo e($flash['message']); ?>
                </div>
            <?php endif; ?>
            
            <?php if ($error): ?>
                <div class="alert alert-danger fade-in"><span>⚠</span> <?php echo e($error); ?></div>
            <?php endif; ?>
            
            <?php if ($success): ?>
                <div class="alert alert-success fade-in"><span>✓</span> <?php echo e($success); ?></div>
            <?php endif; ?>
            
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 24px;">
                <!-- Profile Info -->
                <div class="card">
                    <div class="card-header">
                        <span class="card-title">Personal Information</span>
                    </div>
                    <div class="card-body">
                        <form method="POST" action="">
                            <input type="hidden" name="update_profile" value="1">
                            
                            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px;">
                                <div class="form-group">
                                    <label class="form-label">First Name</label>
                                    <input type="text" name="first_name" class="form-control" value="<?php echo e($user['first_name']); ?>" required>
                                </div>
                                <div class="form-group">
                                    <label class="form-label">Last Name</label>
                                    <input type="text" name="last_name" class="form-control" value="<?php echo e($user['last_name']); ?>" required>
                                </div>
                            </div>
                            
                            <div class="form-group">
                                <label class="form-label">Email</label>
                                <input type="email" class="form-control" value="<?php echo e($user['email']); ?>" disabled style="background: var(--gray-100);">
                                <small style="color: var(--gray);">Email cannot be changed</small>
                            </div>
                            
                            <div class="form-group">
                                <label class="form-label">Phone</label>
                                <input type="tel" name="phone" class="form-control" value="<?php echo e($user['phone']); ?>">
                            </div>
                            
                            <div class="form-group">
                                <label class="form-label">Address</label>
                                <textarea name="address" class="form-control" rows="2"><?php echo e($user['address']); ?></textarea>
                            </div>
                            
                            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px;">
                                <div class="form-group">
                                    <label class="form-label">City</label>
                                    <input type="text" name="city" class="form-control" value="<?php echo e($user['city']); ?>">
                                </div>
                                <div class="form-group">
                                    <label class="form-label">State</label>
                                    <input type="text" name="state" class="form-control" value="<?php echo e($user['state']); ?>">
                                </div>
                            </div>
                            
                            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px;">
                                <div class="form-group">
                                    <label class="form-label">Country</label>
                                    <input type="text" name="country" class="form-control" value="<?php echo e($user['country']); ?>">
                                </div>
                                <div class="form-group">
    <label class="form-label">Zip Code</label>
    <input type="text" name="postal_code" class="form-control" value="<?php echo e($user['postal_code']); ?>">
</div>
                               
                            </div>
                            
                            <div class="form-group">
                                <label class="form-label">Occupation</label>
                                <input type="text" name="occupation" class="form-control" value="<?php echo e($user['occupation']); ?>">
                            </div>
                            
                            <button type="submit" class="btn btn-primary">Update Profile</button>
                        </form>
                    </div>
                </div>
                
                <!-- Change Password & Account Info -->
                <div>
                    <div class="card" style="margin-bottom: 24px;">
                        <div class="card-header">
                            <span class="card-title">Change Password</span>
                        </div>
                        <div class="card-body">
                            <form method="POST" action="">
                                <input type="hidden" name="change_password" value="1">
                                
                                <div class="form-group">
                                    <label class="form-label">Current Password</label>
                                    <input type="password" name="current_password" class="form-control" required>
                                </div>
                                
                                <div class="form-group">
                                    <label class="form-label">New Password</label>
                                    <input type="password" name="new_password" class="form-control" required minlength="6">
                                </div>
                                
                                <div class="form-group">
                                    <label class="form-label">Confirm New Password</label>
                                    <input type="password" name="confirm_password" class="form-control" required>
                                </div>
                                
                                <button type="submit" class="btn btn-primary">Change Password</button>
                            </form>
                        </div>
                    </div>
                    
                    <div class="card">
                        <div class="card-header">
                            <span class="card-title">Account Information</span>
                        </div>
                        <div class="card-body">
                            <div style="display: grid; gap: 16px;">
                                <div style="display: flex; justify-content: space-between; padding-bottom: 12px; border-bottom: 1px solid var(--gray-200);">
                                    <span style="color: var(--gray); font-size: 14px;">Account Number</span>
                                    <span style="font-weight: 600; font-family: monospace;"><?php echo e($user['account_number']); ?></span>
                                </div>
                                <div style="display: flex; justify-content: space-between; padding-bottom: 12px; border-bottom: 1px solid var(--gray-200);">
                                    <span style="color: var(--gray); font-size: 14px;">Account Type</span>
                                    <span style="font-weight: 600;"><?php echo ucfirst(e($user['account_type'])); ?></span>
                                </div>
                                <div style="display: flex; justify-content: space-between; padding-bottom: 12px; border-bottom: 1px solid var(--gray-200);">
                                    <span style="color: var(--gray); font-size: 14px;">KYC Status</span>
                                    <span class="kyc-status <?php echo e($user['kyc_status']); ?>"><?php echo ucfirst(e($user['kyc_status'])); ?></span>
                                </div>
                                <div style="display: flex; justify-content: space-between; padding-bottom: 12px; border-bottom: 1px solid var(--gray-200);">
                                    <span style="color: var(--gray); font-size: 14px;">Member Since</span>
                                    <span style="font-weight: 600;"><?php echo formatDateShort($user['created_at']); ?></span>
                                </div>
                                <div style="display: flex; justify-content: space-between;">
                                    <span style="color: var(--gray); font-size: 14px;">Last Login</span>
                                    <span style="font-weight: 600;"><?php echo $user['last_login'] ? formatDate($user['last_login']) : 'Never'; ?></span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <script src="assets/js/main.js"></script>
</body>
</html>
