<?php
session_start();
require_once __DIR__ . '/db.php';

ini_set('display_errors', 1);
error_reporting(E_ALL);

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

$userId   = $_SESSION['user_id'];
$username = trim($_POST['username'] ?? '');
$new      = $_POST['new_password'] ?? '';
$confirm  = $_POST['confirm_password'] ?? '';

/* fetch user */
$stmt = $conn->prepare("SELECT username, avatar FROM users WHERE id = ?");
$stmt->bind_param("i", $userId);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();

if (!$user) {
    $_SESSION['flash'] = ['type'=>'danger','msg'=>'User not found'];
    header("Location: index.php?page=settings");
    exit;
}

/* username update */
if ($username && $username !== $user['username']) {

    $check = $conn->prepare("SELECT id FROM users WHERE username = ?");
    $check->bind_param("s", $username);
    $check->execute();

    if ($check->get_result()->num_rows > 0) {
        $_SESSION['flash'] = ['type'=>'warning','msg'=>'Username already taken'];
        header("Location: index.php?page=settings");
        exit;
    }

    $upU = $conn->prepare("UPDATE users SET username=? WHERE id=?");
    $upU->bind_param("si", $username, $userId);
    $upU->execute();

    $_SESSION['username'] = $username;
}

/* avatar upload */
if (!empty($_FILES['avatar']['name'])) {

    $file = $_FILES['avatar'];
    $ext  = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    $allowed = ['jpg','jpeg','png','webp'];

    if (!in_array($ext, $allowed)) {
        $_SESSION['flash'] = ['type'=>'danger','msg'=>'Invalid image format'];
        header("Location: index.php?page=settings");
        exit;
    }

    if ($file['size'] > 2 * 1024 * 1024) {
        $_SESSION['flash'] = ['type'=>'danger','msg'=>'Image size exceeds 2MB'];
        header("Location: index.php?page=settings");
        exit;
    }

    $newName = 'u'.$userId.'_'.time().'.'.$ext;
    $path = __DIR__ . '/uploads/avatars/' . $newName;

    if (move_uploaded_file($file['tmp_name'], $path)) {

        if (!empty($user['avatar'])) {
            @unlink(__DIR__ . '/uploads/avatars/' . $user['avatar']);
        }

        $upA = $conn->prepare("UPDATE users SET avatar=? WHERE id=?");
        $upA->bind_param("si", $newName, $userId);
        $upA->execute();

        $_SESSION['avatar'] = $newName;
    }
}

/* password update */
if ($new !== '' || $confirm !== '') {

    if ($new !== $confirm) {
        $_SESSION['flash'] = ['type'=>'danger','msg'=>'Passwords do not match'];
        header("Location: index.php?page=settings");
        exit;
    }

    $hash = password_hash($new, PASSWORD_DEFAULT);
    $upP = $conn->prepare("UPDATE users SET `password`=? WHERE id=?");
    $upP->bind_param("si", $hash, $userId);
    $upP->execute();

    $_SESSION['flash'] = ['type'=>'success','msg'=>'Password updated successfully'];
} else {
    $_SESSION['flash'] = ['type'=>'success','msg'=>'Profile updated successfully'];
}

header("Location: index.php?page=settings");
exit;
