<?php
session_start();
require_once 'connection.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header("Location: login.html");
    exit();
}

$uploadDir = __DIR__ . '/data/';
$accessURL = 'data/';

if (!isset($_FILES['avatar'])) {
    echo "No file uploaded.";
    exit;
}

$file = $_FILES['avatar'];

if ($file['error'] !== UPLOAD_ERR_OK) {
    echo "Upload failed with error code: " . $file['error'];
    exit;
}

// Validate MIME type
$finfo = new finfo(FILEINFO_MIME_TYPE);
$validTypes = ['image/jpeg' => 'jpg', 'image/png' => 'png', 'image/gif' => 'gif'];
$ext = $validTypes[$finfo->file($file['tmp_name'])] ?? false;

if (!$ext) {
    echo "Invalid file type.";
    exit;
}

// Generate unique file name
$newFileName = 'avatar_' . $_SESSION['userid'] . '.' . $ext;
$targetPath = $uploadDir . $newFileName;

if (move_uploaded_file($file['tmp_name'], $targetPath)) {
    echo $accessURL . $newFileName;
} else {
    echo "Failed to move uploaded file.";
}

$_SESSION['profile_photo'] = $newFileName;

$stmt = $pdo->prepare("UPDATE USERS SET PROFILE_PHOTO = :profile_photo WHERE username = :username AND userid = :userid");
$stmt->bindParam(':profile_photo', $_SESSION['profile_photo']);
$stmt->bindParam(':username', $_SESSION['username']);
$stmt->bindParam(':userid', $_SESSION['userid']);
$stmt->execute();
