<?php
session_start();
include('../../includes/config.php');

if (!isset($_SESSION['user_id'])) {
    header("Location: ../../index.php");
    exit();
}

$user_id = $_SESSION['user_id'];
$query = "SELECT first_name, last_name, email, phone_number, profile_picture FROM users WHERE id = ?";
$stmt = $conn->prepare($query);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result()->fetch_assoc();
$stmt->close();

function e($str) {
    return htmlspecialchars($str, ENT_QUOTES, 'UTF-8');
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Edit Profile</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.13/cropper.min.css" rel="stylesheet" />
    <style>
        body { font-family: Arial, sans-serif; background: #f4f4f4; }
        .container {
            max-width: 700px;
            margin: 50px auto;
            background: #fff;
            padding: 30px;
            border-radius: 10px;
            position: relative;
        }
        h2 { text-align: center; }
        label { display: block; margin-top: 15px; }
        input[type="text"], input[type="email"], input[type="password"] {
            width: 100%; padding: 10px; margin-top: 5px; border: 1px solid #ccc;
            border-radius: 5px;
            box-sizing: border-box;
        }
        #preview {
            width: 150px;
            height: 150px;
            margin-top: 15px;
            border-radius: 50%;
            object-fit: cover;
            border: 2px solid #ddd;
        }
        .btn {
            margin-top: 15px; padding: 10px 15px; background: #007bff; color: #fff;
            border: none; border-radius: 5px; cursor: pointer;
            transition: background-color 0.3s;
        }
        .btn:hover {
            background-color: #0056b3;
        }
        .btn-danger { background: #dc3545; }
        .btn-warning { background: #ffc107; color: #000; }
        #cropModal {
            position: fixed;
            top: 0; left: 0; right: 0; bottom: 0;
            background: rgba(0,0,0,0.7);
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 1000;
            flex-direction: column;
        }
        #cropModal img { max-width: 90%; max-height: 90%; border-radius: 10px; }
        #message {
            margin-top: 15px;
            padding: 10px;
            border-radius: 5px;
            display: none;
            font-weight: bold;
        }
        #message.success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        #message.error {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        #loadingSpinner {
            display: none;
            position: absolute;
            top: 10px;
            right: 10px;
            width: 30px;
            height: 30px;
            border: 4px solid #007bff;
            border-top: 4px solid transparent;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            z-index: 1100;
        }
        @keyframes spin {
            0% { transform: rotate(0deg);}
            100% { transform: rotate(360deg);}
        }
    </style>
</head>
<body>

<div class="container">
    <h2>Edit Profile</h2>

    <div id="message"></div>
    <div id="loadingSpinner"></div>

    <form id="profileForm" enctype="multipart/form-data" novalidate>
        <input type="hidden" name="user_id" value="<?= $user_id ?>">

        <label>First Name:</label>
        <input type="text" name="first_name" value="<?= e($result['first_name']) ?>" required>

        <label>Last Name:</label>
        <input type="text" name="last_name" value="<?= e($result['last_name']) ?>" required>

        <label>Email:</label>
        <input type="email" name="email" value="<?= e($result['email']) ?>" required>

        <label>Phone Number:</label>
        <input type="text" name="phone_number" value="<?= e($result['phone_number']) ?>">

        <label>Password (leave blank to keep existing):</label>
        <input type="password" name="password">

        <label>Profile Picture:</label>
        <input type="file" id="fileInput" accept="image/png, image/jpeg, image/jpg, image/webp">
        <img id="preview" src="../../uploads/<?= e($result['profile_picture'] ?: 'default.png') ?>" alt="Profile">
        <input type="hidden" name="cropped_image" id="croppedImage">

        <button type="button" id="deletePic" class="btn btn-danger">Delete Profile Picture</button>
        <button type="button" id="restorePic" class="btn btn-warning">Restore Default Picture</button>

        <button type="submit" class="btn">Update Profile</button>
    </form>
</div>

<!-- Cropper Modal -->
<div id="cropModal">
    <img id="cropImage" alt="Cropper Image">
    <button id="cropBtn" class="btn">Crop</button>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.13/cropper.min.js"></script>
<script>
    const fileInput = document.getElementById('fileInput');
    const cropImage = document.getElementById('cropImage');
    const cropModal = document.getElementById('cropModal');
    const croppedImageInput = document.getElementById('croppedImage');
    const previewImage = document.getElementById('preview');
    const profileForm = document.getElementById('profileForm');
    const messageBox = document.getElementById('message');
    const loadingSpinner = document.getElementById('loadingSpinner');
    let cropper;

    function showMessage(type, text) {
        messageBox.textContent = text;
        messageBox.className = '';
        messageBox.classList.add(type === 'success' ? 'success' : 'error');
        messageBox.style.display = 'block';
    }

    function clearMessage() {
        messageBox.style.display = 'none';
        messageBox.textContent = '';
        messageBox.className = '';
    }

    function validateEmail(email) {
        const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        return re.test(email);
    }

    function validatePhone(phone) {
        if (!phone) return true;
        const re = /^[0-9+\-\s]+$/;
        return re.test(phone);
    }

    function validateFile(file) {
        const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/webp'];
        const maxSize = 2 * 1024 * 1024;
        if (!allowedTypes.includes(file.type)) {
            showMessage('error', 'Invalid image type. Only JPG, PNG, and WEBP allowed.');
            return false;
        }
        if (file.size > maxSize) {
            showMessage('error', 'Image size must be less than 2MB.');
            return false;
        }
        return true;
    }

    fileInput.addEventListener('change', e => {
        clearMessage();
        const file = e.target.files[0];
        if (!file) return;

        if (!validateFile(file)) {
            fileInput.value = '';
            return;
        }

        const reader = new FileReader();
        reader.onload = function(e) {
            cropImage.src = e.target.result;
            cropModal.style.display = 'flex';

            if (cropper) cropper.destroy();
            cropper = new Cropper(cropImage, {
                aspectRatio: 1,
                viewMode: 1
            });
        };
        reader.readAsDataURL(file);
    });

    document.getElementById('cropBtn').addEventListener('click', () => {
        const canvas = cropper.getCroppedCanvas({ width: 150, height: 150 });
        previewImage.src = canvas.toDataURL();
        croppedImageInput.value = canvas.toDataURL();
        cropModal.style.display = 'none';
        cropper.destroy();
    });

    profileForm.addEventListener('submit', e => {
        e.preventDefault();
        clearMessage();

        const formData = new FormData(profileForm);
        const email = formData.get('email').trim();
        const phone = formData.get('phone_number').trim();

        if (!validateEmail(email)) {
            showMessage('error', 'Please enter a valid email address.');
            return;
        }

        if (!validatePhone(phone)) {
            showMessage('error', 'Please enter a valid phone number.');
            return;
        }

        loadingSpinner.style.display = 'block';

        fetch('../../processes/update_profile.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.text())
        .then(data => {
            loadingSpinner.style.display = 'none';
            if (data.toLowerCase().includes('success')) {
                showMessage('success', data);
                setTimeout(() => {
                    window.location.href = 'profile.php';
                }, 2000);
            } else {
                showMessage('error', data);
            }
        })
        .catch(() => {
            loadingSpinner.style.display = 'none';
            showMessage('error', 'An error occurred while updating profile.');
        });
    });

    document.getElementById('deletePic').addEventListener('click', () => {
        clearMessage();
        if (!confirm("Are you sure you want to delete your profile picture?")) return;

        loadingSpinner.style.display = 'block';

        fetch('../../processes/delete_profile_picture.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: new URLSearchParams({ user_id: <?= $user_id ?> })
        })
        .then(res => res.text())
        .then(data => {
            loadingSpinner.style.display = 'none';
            if (data.toLowerCase().includes('success')) {
                showMessage('success', data);
                previewImage.src = '../../uploads/default.png';
            } else {
                showMessage('error', data);
            }
        })
        .catch(() => {
            loadingSpinner.style.display = 'none';
            showMessage('error', 'Failed to delete profile picture.');
        });
    });

    document.getElementById('restorePic').addEventListener('click', () => {
        clearMessage();

        loadingSpinner.style.display = 'block';

        fetch('../../processes/restore_default_picture.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: new URLSearchParams({ user_id: <?= $user_id ?> })
        })
        .then(res => res.text())
        .then(data => {
            loadingSpinner.style.display = 'none';
            if (data.toLowerCase().includes('success')) {
                showMessage('success', data);
                previewImage.src = '../../uploads/default.png';
            } else {
                showMessage('error', data);
            }
        })
        .catch(() => {
            loadingSpinner.style.display = 'none';
            showMessage('error', 'Failed to restore default picture.');
        });
    });
</script>

</body>
</html>
