<?php
/**
 * User - Enhanced Profile
 */
require_once __DIR__ . '/../config.php';
require_login();

$page_title = 'My Profile';
$user_id = $_SESSION['user_id'];

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

// Get user data
$user = [];
try {
    $stmt = db()->prepare("SELECT * FROM users WHERE id = ?");
    $stmt->execute([$user_id]);
    $user = $stmt->fetch();
} catch (PDOException $e) {}

// Update profile
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verify_csrf_token($_POST['csrf_token'] ?? '')) {
        $error = 'Invalid security token';
    } else {
        $full_name = sanitize($_POST['full_name'] ?? '');
        $phone = sanitize($_POST['phone'] ?? '');
        $company = sanitize($_POST['company_name'] ?? '');
        $address = sanitize($_POST['address'] ?? '');
        $city = sanitize($_POST['city'] ?? '');
        $state = sanitize($_POST['state'] ?? '');
        $pincode = sanitize($_POST['pincode'] ?? '');
        
        try {
            $stmt = db()->prepare("UPDATE users SET full_name = ?, phone = ?, company_name = ?, address = ?, city = ?, state = ?, pincode = ? WHERE id = ?");
            $stmt->execute([$full_name, $phone, $company, $address, $city, $state, $pincode, $user_id]);
            $_SESSION['user_name'] = $full_name;
            $success = 'Profile updated successfully';
            
            // Refresh user data
            $stmt = db()->prepare("SELECT * FROM users WHERE id = ?");
            $stmt->execute([$user_id]);
            $user = $stmt->fetch();
        } catch (PDOException $e) {
            $error = 'Failed to update profile';
        }
    }
}

$csrf_token = generate_csrf_token();

// Calculate profile completion
$fields = ['full_name', 'email', 'phone', 'company_name', 'address', 'city', 'state', 'pincode'];
$filled = count(array_filter($fields, fn($f) => !empty($user[$f])));
$completion = round(($filled / count($fields)) * 100);

include __DIR__ . '/includes/header.php';
?>

<style>
.profile-card {
    border: none;
    border-radius: 20px;
    overflow: hidden;
}
.profile-header {
    background: linear-gradient(135deg, #f97316 0%, #ea580c 100%);
    padding: 3rem 2rem 4rem;
    position: relative;
}
.profile-header::after {
    content: '';
    position: absolute;
    bottom: -50px;
    left: 0;
    right: 0;
    height: 100px;
    background: white;
    border-radius: 50% 50% 0 0;
}
.avatar-container {
    width: 120px;
    height: 120px;
    border-radius: 50%;
    background: white;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 10px 30px rgba(0,0,0,0.15);
    position: relative;
    z-index: 10;
    margin-top: -60px;
    margin-bottom: 1rem;
}
.avatar-initials {
    width: 100px;
    height: 100px;
    border-radius: 50%;
    background: linear-gradient(135deg, #f97316 0%, #ea580c 100%);
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 2.5rem;
    font-weight: 700;
}
.completion-ring {
    width: 130px;
    height: 130px;
    border-radius: 50%;
    background: conic-gradient(#10b981 calc(var(--progress) * 1%), #e5e7eb 0);
    display: flex;
    align-items: center;
    justify-content: center;
    position: absolute;
    top: -65px;
    left: 50%;
    transform: translateX(-50%);
    z-index: 5;
}
.form-floating > .form-control:focus ~ label,
.form-floating > .form-control:not(:placeholder-shown) ~ label {
    color: #f97316;
}
.form-floating > .form-control:focus {
    border-color: #f97316;
    box-shadow: 0 0 0 0.25rem rgba(249, 115, 22, 0.1);
}
.info-card {
    background: #f8fafc;
    border-radius: 16px;
    padding: 1.5rem;
}
.info-item {
    display: flex;
    align-items: center;
    padding: 1rem 0;
    border-bottom: 1px solid #e5e7eb;
}
.info-item:last-child {
    border-bottom: none;
}
.info-icon {
    width: 40px;
    height: 40px;
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 1rem;
}
</style>

<!-- Page Header -->
<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h2 class="fw-bold mb-1">My Profile</h2>
        <p class="text-muted mb-0">Manage your personal information and preferences</p>
    </div>
    <a href="change-password.php" class="btn btn-outline-primary">
        <i class="bi bi-shield-lock me-2"></i>Change Password
    </a>
</div>

<?php if ($success): ?>
    <div class="alert alert-success alert-dismissible fade show" role="alert">
        <i class="bi bi-check-circle-fill me-2"></i><?php echo $success; ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
<?php endif; ?>
<?php if ($error): ?>
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
        <i class="bi bi-exclamation-circle-fill me-2"></i><?php echo $error; ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
<?php endif; ?>

<div class="row g-4">
    <!-- Left Column - Profile Info -->
    <div class="col-lg-4">
        <!-- Profile Card -->
        <div class="card profile-card shadow-sm">
            <div class="profile-header text-center text-white">
                <h4 class="fw-bold mb-1"><?php echo $user['full_name']; ?></h4>
                <p class="opacity-90 mb-0"><?php echo $user['email']; ?></p>
            </div>
            
            <div class="card-body text-center pt-0 position-relative">
                <!-- Completion Ring -->
                <div class="completion-ring" style="--progress: <?php echo $completion; ?>">
                    <div class="avatar-container mx-auto">
                        <div class="avatar-initials">
                            <?php echo strtoupper(substr($user['full_name'], 0, 1)); ?>
                        </div>
                    </div>
                </div>
                
                <div class="mt-5 pt-3">
                    <h5 class="fw-bold mb-1"><?php echo $user['full_name']; ?></h5>
                    <p class="text-muted mb-3"><?php echo $user['company_name'] ?: 'No company set'; ?></p>
                    
                    <!-- Profile Completion -->
                    <div class="mb-3">
                        <div class="d-flex justify-content-between mb-2">
                            <small class="text-muted">Profile Completion</small>
                            <small class="fw-bold text-success"><?php echo $completion; ?>%</small>
                        </div>
                        <div class="progress" style="height: 8px;">
                            <div class="progress-bar bg-success" role="progressbar" style="width: <?php echo $completion; ?>%"></div>
                        </div>
                    </div>
                    
                    <?php if ($completion < 100): ?>
                        <p class="text-muted small mb-0">
                            <i class="bi bi-info-circle me-1"></i>
                            Complete your profile for better experience
                        </p>
                    <?php else: ?>
                        <p class="text-success small mb-0">
                            <i class="bi bi-check-circle me-1"></i>
                            Profile complete!
                        </p>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        
        <!-- Account Info -->
        <div class="info-card mt-4">
            <h6 class="fw-bold mb-3"><i class="bi bi-info-circle text-primary me-2"></i>Account Info</h6>
            
            <div class="info-item">
                <div class="info-icon bg-primary bg-opacity-10 text-primary">
                    <i class="bi bi-calendar"></i>
                </div>
                <div>
                    <small class="text-muted d-block">Member Since</small>
                    <span class="fw-medium"><?php echo format_date($user['created_at'], 'F d, Y'); ?></span>
                </div>
            </div>
            
            <div class="info-item">
                <div class="info-icon bg-success bg-opacity-10 text-success">
                    <i class="bi bi-shield-check"></i>
                </div>
                <div>
                    <small class="text-muted d-block">Account Status</small>
                    <span class="badge bg-success"><?php echo ucfirst($user['status']); ?></span>
                </div>
            </div>
            
            <div class="info-item">
                <div class="info-icon bg-warning bg-opacity-10 text-warning">
                    <i class="bi bi-envelope"></i>
                </div>
                <div>
                    <small class="text-muted d-block">Email Status</small>
                    <span class="badge bg-<?php echo $user['email_verified'] ? 'success' : 'warning'; ?>">
                        <?php echo $user['email_verified'] ? 'Verified' : 'Unverified'; ?>
                    </span>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Right Column - Edit Form -->
    <div class="col-lg-8">
        <div class="card profile-card shadow-sm">
            <div class="card-header bg-white border-0 pt-4 pb-0">
                <h5 class="fw-bold mb-0"><i class="bi bi-person-gear text-primary me-2"></i>Edit Profile</h5>
            </div>
            <div class="card-body p-4">
                <form method="POST">
                    <input type="hidden" name="csrf_token" value="<?php echo $csrf_token; ?>">
                    
                    <div class="row g-3">
                        <!-- Personal Info -->
                        <div class="col-12">
                            <h6 class="text-muted text-uppercase small fw-bold mb-3">Personal Information</h6>
                        </div>
                        
                        <div class="col-md-6">
                            <div class="form-floating">
                                <input type="text" name="full_name" class="form-control" id="full_name" 
                                       value="<?php echo $user['full_name'] ?? ''; ?>" placeholder="Full Name" required>
                                <label for="full_name"><i class="bi bi-person me-2"></i>Full Name</label>
                            </div>
                        </div>
                        
                        <div class="col-md-6">
                            <div class="form-floating">
                                <input type="email" class="form-control" id="email" 
                                       value="<?php echo $user['email'] ?? ''; ?>" placeholder="Email" disabled>
                                <label for="email"><i class="bi bi-envelope me-2"></i>Email Address</label>
                            </div>
                            <small class="text-muted">Email cannot be changed</small>
                        </div>
                        
                        <div class="col-md-6">
                            <div class="form-floating">
                                <input type="tel" name="phone" class="form-control" id="phone" 
                                       value="<?php echo $user['phone'] ?? ''; ?>" placeholder="Phone">
                                <label for="phone"><i class="bi bi-phone me-2"></i>Phone Number</label>
                            </div>
                        </div>
                        
                        <div class="col-md-6">
                            <div class="form-floating">
                                <input type="text" name="company_name" class="form-control" id="company" 
                                       value="<?php echo $user['company_name'] ?? ''; ?>" placeholder="Company">
                                <label for="company"><i class="bi bi-building me-2"></i>Company Name</label>
                            </div>
                        </div>
                        
                        <!-- Address Info -->
                        <div class="col-12 mt-4">
                            <h6 class="text-muted text-uppercase small fw-bold mb-3">Address Information</h6>
                        </div>
                        
                        <div class="col-12">
                            <div class="form-floating">
                                <textarea name="address" class="form-control" id="address" 
                                          placeholder="Address" style="height: 80px;"><?php echo $user['address'] ?? ''; ?></textarea>
                                <label for="address"><i class="bi bi-geo-alt me-2"></i>Street Address</label>
                            </div>
                        </div>
                        
                        <div class="col-md-4">
                            <div class="form-floating">
                                <input type="text" name="city" class="form-control" id="city" 
                                       value="<?php echo $user['city'] ?? ''; ?>" placeholder="City">
                                <label for="city"><i class="bi bi-map me-2"></i>City</label>
                            </div>
                        </div>
                        
                        <div class="col-md-4">
                            <div class="form-floating">
                                <input type="text" name="state" class="form-control" id="state" 
                                       value="<?php echo $user['state'] ?? ''; ?>" placeholder="State">
                                <label for="state"><i class="bi bi-map-fill me-2"></i>State</label>
                            </div>
                        </div>
                        
                        <div class="col-md-4">
                            <div class="form-floating">
                                <input type="text" name="pincode" class="form-control" id="pincode" 
                                       value="<?php echo $user['pincode'] ?? ''; ?>" placeholder="Pincode">
                                <label for="pincode"><i class="bi bi-mailbox me-2"></i>Pincode</label>
                            </div>
                        </div>
                    </div>
                    
                    <hr class="my-4">
                    
                    <div class="d-flex justify-content-between align-items-center">
                        <small class="text-muted">
                            <i class="bi bi-shield-check me-1"></i>
                            Your information is secure with us
                        </small>
                        <button type="submit" class="btn btn-primary btn-lg">
                            <i class="bi bi-check-lg me-2"></i>Save Changes
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

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

