<?php
require_once '../includes/auth.php';
require_once '../config/database.php';

$auth = new Auth();
$auth->requireLogin();

header('Content-Type: application/json');

$database = new Database();
$db = $database->getConnection();

$input = json_decode(file_get_contents('php://input'), true);
$action = $input['action'] ?? $_GET['action'] ?? '';

try {
    switch ($action) {
        case 'update_profile':
            $result = updateProfile($db, $input);
            break;
            
        case 'change_password':
            $result = changePassword($db, $input);
            break;
            
        case 'get_profile':
            $result = getProfile($db);
            break;
            
        default:
            throw new Exception('無效的操作');
    }
    
    echo json_encode($result);
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}

function updateProfile($db, $data) {
    $user_id = $_SESSION['user_id'];
    
    $query = "UPDATE users SET 
              username = :username,
              email = :email,
              full_name = :full_name,
              phone = :phone,
              updated_at = NOW()
              WHERE id = :user_id";
    
    $stmt = $db->prepare($query);
    $stmt->bindParam(':username', $data['username']);
    $stmt->bindParam(':email', $data['email']);
    $stmt->bindParam(':full_name', $data['full_name']);
    $stmt->bindParam(':phone', $data['phone']);
    $stmt->bindParam(':user_id', $user_id);
    
    if ($stmt->execute()) {
        return [
            'success' => true,
            'message' => '個人資料更新成功'
        ];
    } else {
        throw new Exception('個人資料更新失敗');
    }
}

function changePassword($db, $data) {
    $user_id = $_SESSION['user_id'];
    $current_password = $data['current_password'];
    $new_password = $data['new_password'];
    
    // 驗證當前密碼
    $query = "SELECT password FROM users WHERE id = :user_id";
    $stmt = $db->prepare($query);
    $stmt->bindParam(':user_id', $user_id);
    $stmt->execute();
    
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!password_verify($current_password, $user['password'])) {
        throw new Exception('當前密碼不正確');
    }
    
    // 更新密碼
    $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
    
    $query = "UPDATE users SET 
              password = :password,
              updated_at = NOW()
              WHERE id = :user_id";
    
    $stmt = $db->prepare($query);
    $stmt->bindParam(':password', $hashed_password);
    $stmt->bindParam(':user_id', $user_id);
    
    if ($stmt->execute()) {
        return [
            'success' => true,
            'message' => '密碼修改成功'
        ];
    } else {
        throw new Exception('密碼修改失敗');
    }
}

function getProfile($db) {
    $user_id = $_SESSION['user_id'];
    
    $query = "SELECT id, username, email, full_name, phone, created_at 
              FROM users WHERE id = :user_id";
    
    $stmt = $db->prepare($query);
    $stmt->bindParam(':user_id', $user_id);
    $stmt->execute();
    
    $profile = $stmt->fetch(PDO::FETCH_ASSOC);
    
    return [
        'success' => true,
        'data' => $profile
    ];
}
?>
