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

if (!isAuthenticated()) {
    redirect(APP_URL . '/login.php');
}

$pageTitle = 'Edit Profile';
$activePage = 'profile';

$db = getDB();
$userId = $_SESSION['user_id'];

// Get current user info
$stmt = $db->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$userId]);
$user = $stmt->fetch();

$message = '';
$error = '';

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'update_profile') {
        $name = sanitizeInput($_POST['name'] ?? '');
        $mobile = sanitizeInput($_POST['mobile'] ?? '');
        
        if (empty($name)) {
            $error = 'Name is required';
        } else {
            // Handle profile photo upload
            $profilePhoto = $user['profile_photo'];
            
            if (isset($_FILES['profile_photo']) && $_FILES['profile_photo']['error'] === UPLOAD_ERR_OK) {
                $allowedTypes = ['image/jpeg', 'image/png', 'image/webp'];
                $fileType = $_FILES['profile_photo']['type'];
                $fileSize = $_FILES['profile_photo']['size'];
                
                if (!in_array($fileType, $allowedTypes)) {
                    $error = 'Invalid file type. Only JPG, PNG, and WEBP are allowed.';
                } else if ($fileSize > 5 * 1024 * 1024) {
                    $error = 'Profile photo must be less than 5MB.';
                } else {
                    $ext = pathinfo($_FILES['profile_photo']['name'], PATHINFO_EXTENSION);
                    $newPhotoName = $user['unique_id'] . '_' . time() . '.' . $ext;
                    $uploadPath = UPLOAD_PATH . 'images/' . $newPhotoName;
                    
                    // Delete old photo if exists
                    if ($profilePhoto && file_exists(UPLOAD_PATH . 'images/' . $profilePhoto)) {
                        unlink(UPLOAD_PATH . 'images/' . $profilePhoto);
                    }
                    
                    if (move_uploaded_file($_FILES['profile_photo']['tmp_name'], $uploadPath)) {
                        $profilePhoto = $newPhotoName;
                    } else {
                        $error = 'Failed to upload photo';
                    }
                }
            }
            
            if (empty($error)) {
                $stmt = $db->prepare("UPDATE users SET name = ?, mobile = ?, profile_photo = ? WHERE id = ?");
                $stmt->execute([$name, $mobile, $profilePhoto, $userId]);
                
                // Update session
                $_SESSION['user_name'] = $name;
                
                $message = 'Profile updated successfully!';
                
                // Refresh user data
                $stmt = $db->prepare("SELECT * FROM users WHERE id = ?");
                $stmt->execute([$userId]);
                $user = $stmt->fetch();
            }
        }
    } elseif ($action === 'remove_photo') {
        // Delete old photo
        if ($user['profile_photo'] && file_exists(UPLOAD_PATH . 'images/' . $user['profile_photo'])) {
            unlink(UPLOAD_PATH . 'images/' . $user['profile_photo']);
        }
        
        $stmt = $db->prepare("UPDATE users SET profile_photo = NULL WHERE id = ?");
        $stmt->execute([$userId]);
        
        $message = 'Profile photo removed';
        
        // Refresh user data
        $stmt = $db->prepare("SELECT * FROM users WHERE id = ?");
        $stmt->execute([$userId]);
        $user = $stmt->fetch();
    }
}

include 'includes/header.php';
?>

<div class="relative flex h-screen w-full flex-col overflow-hidden bg-background-light dark:bg-background-dark max-w-md mx-auto">
    <!-- Header -->
    <header class="flex items-center bg-background-light dark:bg-background-dark p-4 border-b border-slate-200 dark:border-slate-800 sticky top-0 z-10">
        <div class="flex items-center gap-3 flex-1">
            <a href="profile.php" class="text-slate-600 dark:text-slate-400 hover:text-primary transition-colors">
                <span class="material-symbols-outlined">arrow_back</span>
            </a>
            <h2 class="text-slate-900 dark:text-slate-100 text-xl font-bold">Edit Profile</h2>
        </div>
    </header>

    <main class="flex-1 overflow-y-auto no-scrollbar pb-24">
        <?php if ($message): ?>
        <div class="m-4 bg-green-100 dark:bg-green-900/20 border border-green-200 dark:border-green-800 text-green-700 dark:text-green-400 px-4 py-3 rounded-xl text-sm">
            <?php echo $message; ?>
        </div>
        <?php endif; ?>
        
        <?php if ($error): ?>
        <div class="m-4 bg-red-100 dark:bg-red-900/20 border border-red-200 dark:border-red-800 text-red-700 dark:text-red-400 px-4 py-3 rounded-xl text-sm">
            <?php echo $error; ?>
        </div>
        <?php endif; ?>

        <!-- Profile Photo Section -->
        <div class="p-6 text-center border-b border-slate-200 dark:border-slate-800">
            <div class="relative inline-block mb-4">
                <?php if ($user['profile_photo']): ?>
                <div id="photo-preview" class="bg-center bg-no-repeat aspect-square bg-cover rounded-full h-28 w-28 border-4 border-primary/20 mx-auto" style="background-image: url('uploads/images/<?php echo htmlspecialchars($user['profile_photo']); ?>')"></div>
                <?php else: ?>
                <div id="photo-preview" class="size-28 rounded-full bg-primary/10 flex items-center justify-center border-4 border-primary/20 mx-auto">
                    <span class="material-symbols-outlined text-5xl text-primary">person</span>
                </div>
                <?php endif; ?>
                
                <label for="profile_photo" class="absolute bottom-0 right-0 size-10 bg-primary text-white rounded-full flex items-center justify-center shadow-lg cursor-pointer hover:bg-primary/90 transition-colors">
                    <span class="material-symbols-outlined">camera_alt</span>
                </label>
            </div>
            
            <p class="text-sm text-slate-500 dark:text-slate-400 mb-2">Tap camera to change photo</p>
            
            <?php if ($user['profile_photo']): ?>
            <form method="POST" action="" class="inline">
                <input type="hidden" name="action" value="remove_photo">
                <button type="submit" class="text-sm text-red-500 hover:text-red-600 font-medium">
                    Remove Photo
                </button>
            </form>
            <?php endif; ?>
        </div>

        <!-- Edit Form -->
        <form method="POST" action="" enctype="multipart/form-data" class="p-4 space-y-4">
            <input type="hidden" name="action" value="update_profile">
            <input type="file" id="profile_photo" name="profile_photo" accept="image/jpeg,image/png,image/webp" class="hidden" onchange="previewPhoto(this)">
            
            <label class="flex flex-col w-full">
                <p class="text-slate-700 dark:text-slate-300 text-sm font-medium leading-normal pb-1.5 ml-1">Full Name <span class="text-red-500">*</span></p>
                <div class="relative">
                    <span class="material-symbols-outlined absolute left-4 top-1/2 -translate-y-1/2 text-slate-400" style="font-size: 20px;">person</span>
                    <input name="name" value="<?php echo htmlspecialchars($user['name']); ?>" class="form-input flex w-full rounded-xl text-slate-900 dark:text-slate-100 focus:outline-0 focus:ring-2 focus:ring-primary/50 border border-slate-200 dark:border-slate-800 bg-white dark:bg-slate-900/50 h-14 placeholder:text-slate-400 pl-11 pr-4 text-base font-normal" placeholder="Your name" type="text" required/>
                </div>
            </label>

            <label class="flex flex-col w-full">
                <p class="text-slate-700 dark:text-slate-300 text-sm font-medium leading-normal pb-1.5 ml-1">Mobile Number</p>
                <div class="relative">
                    <span class="material-symbols-outlined absolute left-4 top-1/2 -translate-y-1/2 text-slate-400" style="font-size: 20px;">smartphone</span>
                    <input name="mobile" value="<?php echo htmlspecialchars($user['mobile']); ?>" class="form-input flex w-full rounded-xl text-slate-900 dark:text-slate-100 focus:outline-0 focus:ring-2 focus:ring-primary/50 border border-slate-200 dark:border-slate-800 bg-white dark:bg-slate-900/50 h-14 placeholder:text-slate-400 pl-11 pr-4 text-base font-normal" placeholder="Your mobile number" type="tel"/>
                </div>
            </label>

            <!-- Read Only Fields -->
            <div class="p-4 bg-slate-100 dark:bg-slate-800/50 rounded-xl space-y-3">
                <div class="flex items-center gap-3">
                    <span class="material-symbols-outlined text-slate-500">badge</span>
                    <div class="flex-1">
                        <p class="text-xs text-slate-500">Unique ID</p>
                        <p class="text-sm font-medium text-slate-900 dark:text-white">@<?php echo htmlspecialchars($user['unique_id']); ?></p>
                    </div>
                </div>
                <div class="flex items-center gap-3">
                    <span class="material-symbols-outlined text-slate-500">email</span>
                    <div class="flex-1">
                        <p class="text-xs text-slate-500">Email</p>
                        <p class="text-sm font-medium text-slate-900 dark:text-white"><?php echo htmlspecialchars($user['email']); ?></p>
                    </div>
                </div>
            </div>

            <button type="submit" class="mt-6 flex h-14 w-full items-center justify-center rounded-xl bg-primary px-4 text-base font-bold tracking-wide text-white transition-opacity active:opacity-90">
                Save Changes
            </button>
        </form>
    </main>
</div>

<script>
    function previewPhoto(input) {
        const preview = document.getElementById('photo-preview');
        if (input.files && input.files[0]) {
            const reader = new FileReader();
            reader.onload = function(e) {
                if (preview.tagName === 'DIV' && !preview.style.backgroundImage) {
                    // Replace icon div with image background
                    preview.style.backgroundImage = "url('" + e.target.result + "')";
                    preview.innerHTML = '';
                } else {
                    preview.style.backgroundImage = "url('" + e.target.result + "')";
                }
            };
            reader.readAsDataURL(input.files[0]);
            
            showToast('Photo selected. Click Save to apply.', 'success');
        }
    }
</script>

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