<?php
session_start();
require_once(__DIR__ . "/../config/db.php");
require_once(__DIR__ . "/../session.php");

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $csrf_token = $_POST['csrf_token'] ?? '';
    if ($csrf_token !== $_SESSION['csrf_token']) {
        $_SESSION['error'] = "Token CSRF tidak valid.";
        header("Location: /");
        exit();
    }

    $fullname = $_POST['FullName'];
    $gender = $_POST['Gender'];
    $address = $_POST['Address'];
    $postcode = $_POST['Postcode'];
    $state = $_POST['State'];
    $country = $_POST['Country'];
    $phone = $_POST['ContactNo'];
    $email = $_POST['Email'];
    $telegram = $_POST['Telegram'];
    $whatsapp = $_POST['WhatsApp'];
    $wechat = $_POST['WeChat'];
    $line = $_POST['Line'];

    if (isset($fullname, $gender, $address, $postcode, $state, $country, $phone, $email, $telegram, $whatsapp, $wechat, $line)) {
        
        $query = "UPDATE user SET fullname = :fullname, gender = :gender, address = :address, postcode = :postcode, state = :state, country = :country, phone = :phone, email = :email, telegram = :telegram, whatsapp = :whatsapp, wechat = :wechat, line = :line WHERE id = :user_id";
        
        $stmt = $db->prepare($query);
        $stmt->bindParam(':fullname', $fullname);
        $stmt->bindParam(':gender', $gender);
        $stmt->bindParam(':address', $address);
        $stmt->bindParam(':postcode', $postcode);
        $stmt->bindParam(':state', $state);
        $stmt->bindParam(':country', $country);
        $stmt->bindParam(':phone', $phone);
        $stmt->bindParam(':email', $email);
        $stmt->bindParam(':telegram', $telegram);
        $stmt->bindParam(':whatsapp', $whatsapp);
        $stmt->bindParam(':wechat', $wechat);
        $stmt->bindParam(':line', $line);
        $stmt->bindParam(':user_id', $user_id);

        if ($stmt->execute()) {
            $_SESSION['message'] = "Data berhasil diperbaharui";
            header("Location: /");
            exit();
        } else {
            $_SESSION['error'] = "Terjadi kesalahan. Silakan coba lagi.";
            header("Location: /");
            exit();
        }
    }
}
?>
