<?php
require_once 'includes/auth.php';
requireLogin();
require_once 'includes/functions.php';

$id = $_SESSION['member_id'];

// ดึงข้อมูลสมาชิก
$stmt = $conn->prepare("SELECT * FROM members WHERE id=?");
$stmt->bind_param("i", $id);
$stmt->execute();

$result = $stmt->get_result();
$member = $result->fetch_assoc();

$stmt->close();

$message = "";
$messageType = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    requireValidCsrf();

    $prefix      = trim($_POST['prefix']);
    $first_name  = trim($_POST['first_name']);
    $last_name   = trim($_POST['last_name']);
    $gender      = trim($_POST['gender']);
    $phone       = trim($_POST['phone']);
    $email       = trim($_POST['email']);
    $address     = trim($_POST['address']);
    $workplace   = trim($_POST['workplace']);
    $position    = trim($_POST['position']);

    $photo = $member['photo'];

    $newPhoto = '';

    if (isset($_FILES['photo'])) {
        $upload = saveUploadedImage(
            $_FILES['photo'],
            'uploads/profiles/'
        );

        if (!$upload['ok']) {
            $message = $upload['error'];
            $messageType = 'warning';
        } elseif ($upload['filename'] !== '') {
            $newPhoto = $upload['filename'];
            $photo = $newPhoto;
        }
    }

    if ($message === '') {
    $stmt = $conn->prepare("
        UPDATE members
        SET
            prefix=?,
            first_name=?,
            last_name=?,
            gender=?,
            phone=?,
            email=?,
            address=?,
            workplace=?,
            position=?,
            photo=?
        WHERE id=?
    ");

    $stmt->bind_param(
        "ssssssssssi",
        $prefix,
        $first_name,
        $last_name,
        $gender,
        $phone,
        $email,
        $address,
        $workplace,
        $position,
        $photo,
        $id
    );

    if ($stmt->execute()) {
        if ($newPhoto !== '') {
            deleteUploadedImage('uploads/profiles/', $member['photo']);
        }

        $_SESSION['fullname'] = $prefix . " " . $first_name . " " . $last_name;

        $message = "บันทึกข้อมูลเรียบร้อยแล้ว";
        $messageType = "success";

        $stmt->close();
        $stmt = $conn->prepare("SELECT * FROM members WHERE id=?");
        $stmt->bind_param("i", $id);
        $stmt->execute();

        $result = $stmt->get_result();
        $member = $result->fetch_assoc();

    }

    $stmt->close();
    } elseif ($newPhoto !== '') {
        deleteUploadedImage('uploads/profiles/', $newPhoto);
    }

}

include 'includes/header.php';
?>

<div class="container mt-5">

    <h2 class="mb-4">
        ✏️ แก้ไขข้อมูลสมาชิก
    </h2>

    <?php if ($message != ""): ?>

        <div class="alert alert-<?= $messageType ?>">
            <?= $message ?>
        </div>

    <?php endif; ?>

    <form method="post" enctype="multipart/form-data">
        <input type="hidden" name="csrf_token" value="<?= htmlspecialchars(csrfToken()) ?>">

        <div class="card shadow">

            <div class="card-body">

                <div class="text-center mb-4">

                    <?php
                    $imagePath = "uploads/profiles/" . $member['photo'];

                    if (!empty($member['photo']) && file_exists(__DIR__ . "/" . $imagePath)):
                    ?>

                        <img
                            src="<?= $imagePath; ?>"
                            class="rounded-circle shadow"
                            style="width:180px;height:180px;object-fit:cover;">

                    <?php else: ?>

                        <div
                            class="rounded-circle bg-secondary text-white d-inline-flex justify-content-center align-items-center shadow"
                            style="width:180px;height:180px;font-size:60px;">

                            👤

                        </div>

                    <?php endif; ?>

                </div>

                <div class="mb-4">

                    <label class="form-label fw-bold">
                        📷 รูปโปรไฟล์
                    </label>

                    <input
                        type="file"
                        name="photo"
                        class="form-control"
                        accept=".jpg,.jpeg,.png,image/jpeg,image/png">

                    <small class="text-muted">
                        รองรับไฟล์ JPG, JPEG และ PNG
                    </small>

                </div>

                <div class="row">

                    <div class="col-md-2 mb-3">

                        <label class="form-label">คำนำหน้า</label>

                        <select name="prefix" class="form-select">
                            <option value="นาย" <?= $member['prefix']=="นาย"?"selected":""; ?>>นาย</option>
                            <option value="นาง" <?= $member['prefix']=="นาง"?"selected":""; ?>>นาง</option>
                            <option value="นางสาว" <?= $member['prefix']=="นางสาว"?"selected":""; ?>>นางสาว</option>
                            <option value="พระ" <?= $member['prefix']=="พระ"?"selected":""; ?>>พระ</option>
                            <option value="สามเณร" <?= $member['prefix']=="สามเณร"?"selected":""; ?>>สามเณร</option>
                        </select>

                    </div>

                    <div class="col-md-5 mb-3">

                        <label class="form-label">ชื่อ</label>

                        <input
                            type="text"
                            name="first_name"
                            class="form-control"
                            value="<?= htmlspecialchars($member['first_name']); ?>"
                            required>

                    </div>

                    <div class="col-md-5 mb-3">

                        <label class="form-label">นามสกุล</label>

                        <input
                            type="text"
                            name="last_name"
                            class="form-control"
                            value="<?= htmlspecialchars($member['last_name']); ?>"
                            required>

                    </div>

                </div>

                <div class="row">

                    <div class="col-md-4 mb-3">

                        <label class="form-label">เพศ</label>

                        <select name="gender" class="form-select">
                            <option value="ชาย" <?= $member['gender']=="ชาย"?"selected":""; ?>>ชาย</option>
                            <option value="หญิง" <?= $member['gender']=="หญิง"?"selected":""; ?>>หญิง</option>
                            <option value="อื่น ๆ" <?= $member['gender']=="อื่น ๆ"?"selected":""; ?>>อื่น ๆ</option>
                        </select>

                    </div>

                    <div class="col-md-4 mb-3">

                        <label class="form-label">เบอร์โทรศัพท์</label>

                        <input
                            type="text"
                            name="phone"
                            class="form-control"
                            value="<?= htmlspecialchars($member['phone']); ?>">

                    </div>

                    <div class="col-md-4 mb-3">

                        <label class="form-label">อีเมล</label>

                        <input
                            type="email"
                            name="email"
                            class="form-control"
                            value="<?= htmlspecialchars($member['email']); ?>">

                    </div>

                </div>

                <div class="mb-3">

                    <label class="form-label">ที่อยู่</label>

                    <textarea
                        name="address"
                        rows="4"
                        class="form-control"><?= htmlspecialchars($member['address']); ?></textarea>

                </div>

                <div class="row">

                    <div class="col-md-6 mb-3">

                        <label class="form-label">สถานที่ทำงาน</label>

                        <input
                            type="text"
                            name="workplace"
                            class="form-control"
                            value="<?= htmlspecialchars($member['workplace']); ?>">

                    </div>

                    <div class="col-md-6 mb-3">

                        <label class="form-label">ตำแหน่งงาน</label>

                        <input
                            type="text"
                            name="position"
                            class="form-control"
                            value="<?= htmlspecialchars($member['position']); ?>">

                    </div>

                </div>

                <div class="mt-4">

                    <button
                        type="submit"
                        class="btn btn-success">

                        💾 บันทึกข้อมูล

                    </button>

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

                        ยกเลิก

                    </a>

                </div>

            </div>

        </div>

    </form>

</div>

<?php
$conn->close();
include 'includes/footer.php';
?>
