<?php

include "../includes/member_auth.php";
include "../config/database.php";

$user_id = $_SESSION['user_id'];


/* GET MEMBER */

$stmt = $pdo->prepare("
    SELECT fullname, email, phone, profile_picture
    FROM users
    WHERE id = ?
    LIMIT 1
");

$stmt->execute([$user_id]);

$user = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$user) {
    header("Location: dashboard.php");
    exit();
}


/* UPDATE PROFILE */

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $fullname = trim($_POST['fullname'] ?? '');
    $email    = trim($_POST['email'] ?? '');
    $phone    = trim($_POST['phone'] ?? '');

    $profilePicture = $user['profile_picture'];

    $error = null;


    /* KEEP OLD VALUES IF LEFT EMPTY */

    if ($fullname === '') {
        $fullname = $user['fullname'];
    }

    if ($phone === '') {
        $phone = $user['phone'];
    }


    /*
    |--------------------------------------------------------------------------
    | EMAIL
    |--------------------------------------------------------------------------
    |
    | Email is OPTIONAL.
    |
    */

    if ($email !== '') {

        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {

            $error = "Please enter a valid email address.";

        }

    }


    /*
    |--------------------------------------------------------------------------
    | CHECK DUPLICATE EMAIL
    |--------------------------------------------------------------------------
    */

    if ($error === null && $email !== '') {

        $stmt = $pdo->prepare("
            SELECT id
            FROM users
            WHERE email = ?
            AND id != ?
            LIMIT 1
        ");

        $stmt->execute([
            $email,
            $user_id
        ]);

        if ($stmt->fetch()) {

            $error = "This email address is already in use.";

        }

    }


    /*
    |--------------------------------------------------------------------------
    | PROFILE PICTURE
    |--------------------------------------------------------------------------
    */

    if (
        $error === null &&
        isset($_FILES['profile_picture']) &&
        $_FILES['profile_picture']['error'] !== UPLOAD_ERR_NO_FILE
    ) {


        if ($_FILES['profile_picture']['error'] !== UPLOAD_ERR_OK) {

            $error = "There was a problem uploading the picture.";

        }


        /* 5MB LIMIT */

        if (
            $error === null &&
            $_FILES['profile_picture']['size'] > (5 * 1024 * 1024)
        ) {

            $error = "Profile picture must not be larger than 5MB.";

        }


        /* CHECK IMAGE */

        if ($error === null) {

            $imageInfo = getimagesize(
                $_FILES['profile_picture']['tmp_name']
            );

            if ($imageInfo === false) {

                $error = "Please upload a valid image.";

            }

        }


        /* ALLOWED TYPES */

        if ($error === null) {

            $allowedTypes = [
                'image/jpeg' => 'jpg',
                'image/png'  => 'png',
                'image/webp' => 'webp'
            ];

            $mimeType = $imageInfo['mime'];

            if (!isset($allowedTypes[$mimeType])) {

                $error =
                    "Only JPG, PNG and WEBP images are allowed.";

            }

        }


        /* SAVE IMAGE */

        if ($error === null) {

            $uploadDir = "../uploads/profile/";


            if (!is_dir($uploadDir)) {

                mkdir($uploadDir, 0755, true);

            }


            $extension = $allowedTypes[$mimeType];


            $newFileName =
                "profile_" .
                $user_id .
                "_" .
                time() .
                "." .
                $extension;


            $destination =
                $uploadDir . $newFileName;


            if (
                move_uploaded_file(
                    $_FILES['profile_picture']['tmp_name'],
                    $destination
                )
            ) {


                /* DELETE OLD PICTURE */

                if (!empty($profilePicture)) {

                    $oldPicture =
                        $uploadDir . basename($profilePicture);

                    if (
                        file_exists($oldPicture) &&
                        is_file($oldPicture)
                    ) {

                        unlink($oldPicture);

                    }

                }


                $profilePicture = $newFileName;

            } else {

                $error =
                    "Unable to save the uploaded picture.";

            }

        }

    }


    /*
    |--------------------------------------------------------------------------
    | SAVE TO DATABASE
    |--------------------------------------------------------------------------
    */

    if ($error === null) {


        $stmt = $pdo->prepare("
            UPDATE users
            SET
                fullname = ?,
                email = ?,
                phone = ?,
                profile_picture = ?
            WHERE id = ?
        ");


        $stmt->execute([
            $fullname,
            $email,
            $phone,
            $profilePicture,
            $user_id
        ]);


        $_SESSION['fullname'] = $fullname;


        $_SESSION['success'] =
            "Profile updated successfully.";


        header("Location: edit_profile.php");

        exit();

    }


    /* SHOW ERROR */

    $_SESSION['error'] = $error;

}

?>

<!DOCTYPE html>
<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport"
content="width=device-width, initial-scale=1.0">

<title>Edit Profile</title>


<link rel="stylesheet"
href="../assets/css/admin.css">

<link rel="stylesheet"
href="../assets/css/responsive.css">

<link rel="stylesheet"
href="../assets/css/member.css">


<link rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css">

</head>


<body>


<?php include "../includes/member_sidebar.php"; ?>

<div class="sidebar-overlay"></div>

<?php include "../includes/member_topbar.php"; ?>


<div class="main-content">


<div class="page-header">

<div>

<h1>

<i class="fas fa-user-pen"></i>

Edit Profile

</h1>

<p>
Update your personal information and profile picture.
</p>

</div>

</div>


<div class="activity-card profile-edit-card">


<div class="activity-title-wrap">

<i class="fas fa-user"></i>

<h3>Personal Information</h3>

</div>


<form
method="POST"
enctype="multipart/form-data"
>


<!-- PROFILE PICTURE -->

<div class="profile-picture-upload">


<div class="profile-preview">


<?php if (!empty($user['profile_picture'])): ?>

<img
src="../uploads/profile/<?= htmlspecialchars($user['profile_picture']); ?>"
alt="Profile Picture"
id="profilePreview"
>

<?php else: ?>

<div
class="profile-placeholder"
id="profilePlaceholder"
>

<i class="fas fa-user"></i>

</div>

<img
src=""
alt="Profile Picture"
id="profilePreview"
style="display:none;"
>

<?php endif; ?>

</div>


<div class="profile-upload-info">


<label
for="profile_picture"
class="profile-upload-btn"
>

<i class="fas fa-camera"></i>

Choose Picture

</label>


<input
type="file"
name="profile_picture"
id="profile_picture"
accept=".jpg,.jpeg,.png,.webp"
hidden
>


<p>

JPG, PNG or WEBP

<br>

Maximum size: 5MB

</p>

</div>


</div>


<!-- FORM -->

<div class="profile-form-grid">


<div class="form-group">

<label>
Full Name
</label>

<input
type="text"
name="fullname"
value="<?= htmlspecialchars($user['fullname'] ?? ''); ?>"
>

</div>


<div class="form-group">

<label>
Email Address
</label>

<input
type="email"
name="email"
value="<?= htmlspecialchars($user['email'] ?? ''); ?>"
>

</div>


<div class="form-group">

<label>
Phone Number
</label>

<input
type="text"
name="phone"
value="<?= htmlspecialchars($user['phone'] ?? ''); ?>"
>

</div>


</div>


<div class="profile-form-actions">


<a
href="profile.php"
class="profile-cancel-btn"
>

<i class="fas fa-arrow-left"></i>

Cancel

</a>


<button
type="submit"
class="profile-save-btn"
>

<i class="fas fa-save"></i>

Save Changes

</button>


</div>


</form>


</div>


<div class="activity-card">


<div class="activity-title-wrap">

<i class="fas fa-shield-halved"></i>

<h3>Account Security</h3>

</div>


<p class="profile-security-note">

Wallet balance, account status and virtual account
information cannot be changed from this page.

</p>


</div>


</div>


<script>

/* PROFILE IMAGE PREVIEW */

const profileInput =
document.getElementById("profile_picture");

const profilePreview =
document.getElementById("profilePreview");

const profilePlaceholder =
document.getElementById("profilePlaceholder");


profileInput.addEventListener("change", function () {

    const file = this.files[0];

    if (!file) {
        return;
    }


    const allowedTypes = [
        "image/jpeg",
        "image/png",
        "image/webp"
    ];


    if (!allowedTypes.includes(file.type)) {

        Swal.fire({
            icon: "error",
            title: "Invalid Image",
            text: "Please choose a JPG, PNG or WEBP image."
        });

        this.value = "";

        return;

    }


    if (file.size > 5 * 1024 * 1024) {

        Swal.fire({
            icon: "error",
            title: "Image Too Large",
            text: "Profile picture must not exceed 5MB."
        });

        this.value = "";

        return;

    }


    const reader = new FileReader();


    reader.onload = function (e) {

        profilePreview.src = e.target.result;

        profilePreview.style.display = "block";


        if (profilePlaceholder) {

            profilePlaceholder.style.display = "none";

        }

    };


    reader.readAsDataURL(file);

});

</script>


<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>


<?php if (isset($_SESSION['success'])): ?>

<script>

Swal.fire({

    icon: "success",

    title: "Profile Updated",

    text: "Profile updated successfully.",

    confirmButtonColor: "#0D6EFD"

});

</script>

<?php

unset($_SESSION['success']);

endif;

?>


<?php if (isset($_SESSION['error'])): ?>

<script>

Swal.fire({

    icon: "error",

    title: "Update Failed",

    text: "<?= htmlspecialchars(
        $_SESSION['error'],
        ENT_QUOTES
    ); ?>",

    confirmButtonColor: "#DC2626"

});

</script>

<?php

unset($_SESSION['error']);

endif;

?>


<script src="../assets/js/member.js"></script>


</body>

</html>