<?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'] ?? '';

$stmt = $conn->prepare("SELECT username, avatar FROM users WHERE id = ?");
$stmt->bind_param("i", $userId);
$stmt->execute();
$stmt->bind_result($dbUsername, $dbAvatar);
$stmt->fetch();
$stmt->close();

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

if ($username && $username !== $dbUsername) {

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

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

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

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

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($dbAvatar)) {
            @unlink(__DIR__ . '/uploads/avatars/' . $dbAvatar);
        }

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

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

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();
    $upP->close();

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

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