<?php
require_once 'includes/session.php';

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

if(isset($_POST['update_profile'])) {
    $name = escape($_POST['name']);
    $designation = escape($_POST['designation']);
    $address = escape($_POST['address']);
    
    // Handle file upload
    $photo_query = "";
    if(isset($_FILES['photo']) && $_FILES['photo']['error'] == 0) {
        $allowed = ['jpg', 'jpeg', 'png'];
        $filename = $_FILES['photo']['name'];
        $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
        
        if(in_array($ext, $allowed)) {
            $new_name = 'user_' . $member['id'] . '_' . time() . '.' . $ext;
            $upload_dir = '../assets/uploads/';
            
            // Create dir if not exists
            if(!is_dir($upload_dir)) {
                mkdir($upload_dir, 0755, true);
            }
            
            if(move_uploaded_file($_FILES['photo']['tmp_name'], $upload_dir . $new_name)) {
                $photo_query = ", photo='$new_name'";
                
                // Delete old photo
                if(!empty($member['photo']) && file_exists($upload_dir . $member['photo'])) {
                    unlink($upload_dir . $member['photo']);
                }
                $member['photo'] = $new_name; // Update local session array for UI display
            } else {
                $error = "Failed to upload photo.";
            }
        } else {
            $error = "Invalid file format. Only JPG, JPEG, PNG allowed.";
        }
    }
    
    if(!$error) {
        $query = "UPDATE users SET name='$name', designation='$designation', address='$address' $photo_query WHERE id='{$member['id']}'";
        if($conn->query($query)) {
            $success = "Profile updated successfully!";
            $member['name'] = $name;
            $member['designation'] = $designation;
            $member['address'] = $address;
            $_SESSION['member_name'] = $name;
        } else {
            $error = "Failed to update profile.";
        }
    }
}

require_once '../includes/header.php'; 
?>

<div class="container-fluid min-vh-100 py-5" style="background: #f1f5f9;">
    <div class="container">
        
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2 class="fw-bold text-dark">Update Profile</h2>
            <a href="index.php" class="btn btn-outline-secondary btn-sm rounded-pill px-3 shadow-sm"><i class="fas fa-arrow-left"></i> Back to Dashboard</a>
        </div>

        <div class="card border-0 shadow-sm rounded-4">
            <div class="card-body p-4 p-md-5">
                
                <?php if($error): ?>
                    <div class="alert alert-danger fw-bold"><i class="fas fa-exclamation-circle me-2"></i> <?php echo $error ?></div>
                <?php endif; ?>
                <?php if($success): ?>
                    <div class="alert alert-success fw-bold"><i class="fas fa-check-circle me-2"></i> <?php echo $success ?></div>
                <?php endif; ?>

                <form action="profile.php" method="POST" enctype="multipart/form-data">
                    <div class="row">
                        <!-- Photo Upload Section -->
                        <div class="col-md-4 text-center mb-4 mb-md-0">
                            <div class="mb-3 position-relative d-inline-block">
                                <?php if(!empty($member['photo'])): ?>
                                    <img src="../assets/uploads/<?php echo $member['photo']; ?>" id="photo-preview" class="rounded-circle border shadow-sm" style="width: 150px; height: 150px; object-fit: cover;" alt="Profile Photo">
                                <?php else: ?>
                                    <div id="photo-placeholder" class="rounded-circle bg-secondary d-inline-flex align-items-center justify-content-center text-white shadow-sm" style="width: 150px; height: 150px; font-size: 4rem;">
                                        <i class="fas fa-user"></i>
                                    </div>
                                    <img src="#" id="photo-preview" class="rounded-circle border shadow-sm d-none" style="width: 150px; height: 150px; object-fit: cover;" alt="Profile Photo">
                                <?php endif; ?>
                            </div>
                            <div>
                                <label for="photo-upload" class="btn btn-outline-primary btn-sm rounded-pill fw-bold">
                                    <i class="fas fa-camera me-1"></i> Change Photo
                                </label>
                                <input type="file" id="photo-upload" name="photo" class="d-none" accept=".jpg,.jpeg,.png" onchange="previewImage(this)">
                                <div class="small text-muted mt-2">Recommended: Square image, max 2MB.</div>
                            </div>
                        </div>

                        <!-- Form Fields -->
                        <div class="col-md-8">
                            <div class="row g-3">
                                <div class="col-12">
                                    <label class="form-label fw-bold">Full Name <span class="text-danger">*</span></label>
                                    <input type="text" name="name" class="form-control bg-light border-0 py-2" value="<?php echo h($member['name']); ?>" required>
                                </div>
                                <div class="col-12">
                                    <label class="form-label fw-bold">Designation</label>
                                    <input type="text" name="designation" class="form-control bg-light border-0 py-2" value="<?php echo h($member['designation'] ?? ''); ?>" placeholder="e.g. State President, Member, etc.">
                                </div>
                                <div class="col-12">
                                    <label class="form-label fw-bold">Email ID (Cannot be changed)</label>
                                    <input type="email" class="form-control bg-light border-0 py-2 text-muted" value="<?php echo h($member['email'] ?? ''); ?>" readonly disabled>
                                </div>
                                <div class="col-12">
                                    <label class="form-label fw-bold">Phone Number (Cannot be changed)</label>
                                    <input type="text" class="form-control bg-light border-0 py-2 text-muted" value="<?php echo h($member['phone'] ?? ''); ?>" readonly disabled>
                                </div>
                                <div class="col-12">
                                    <label class="form-label fw-bold">Address</label>
                                    <textarea name="address" class="form-control bg-light border-0 py-2" rows="3"><?php echo h($member['address'] ?? ''); ?></textarea>
                                </div>
                                <div class="col-12 mt-4 text-end">
                                    <button type="submit" name="update_profile" class="btn btn-primary rounded-pill px-5 fw-bold shadow">Save Changes</button>
                                </div>
                            </div>
                        </div>
                    </div>
                </form>

            </div>
        </div>
    </div>
</div>

<script>
function previewImage(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function(e) {
            var preview = document.getElementById('photo-preview');
            var placeholder = document.getElementById('photo-placeholder');
            if(placeholder) placeholder.classList.add('d-none');
            preview.classList.remove('d-none');
            preview.src = e.target.result;
        }
        reader.readAsDataURL(input.files[0]);
    }
}
</script>

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