<?php
session_start();
require_once "../includes/db.php";

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

$user_id = $_SESSION['user_id'];

// ✅ Check file input
if (!isset($_FILES['photo']) || $_FILES['photo']['error'] !== UPLOAD_ERR_OK) {
    header("Location: ../users/profile_photo?error=Please select a valid image");
    exit;
}

// ✅ Validate file type
$allowed = ['image/jpeg', 'image/png', 'image/jpg'];
if (!in_array($_FILES['photo']['type'], $allowed)) {
    header("Location: ../users/profile_photo?error=Only JPEG and PNG images are allowed");
    exit;
}

// ✅ Get current photo to delete the old one
$stmt = $pdo->prepare("SELECT photo FROM users WHERE id = ?");
$stmt->execute([$user_id]);
$currentPhoto = $stmt->fetchColumn();

// ✅ Generate new unique filename
$ext = pathinfo($_FILES['photo']['name'], PATHINFO_EXTENSION);
$filename = time() . "_" . uniqid() . "." . $ext;
$path = "../users/uploads/" . $filename;

// ✅ Upload new file
if (!move_uploaded_file($_FILES['photo']['tmp_name'], $path)) {
    header("Location: ../users/profile_photo?error=Upload failed, try again");
    exit;
}

// ✅ Delete old photo (ONLY if not default.png and file exists)
if ($currentPhoto && $currentPhoto !== 'default.png') {
    $oldFilePath = "../users/uploads/" . $currentPhoto;
    if (file_exists($oldFilePath)) {
        unlink($oldFilePath);
    }
}

// ✅ Update database
$stmt = $pdo->prepare("UPDATE users SET photo = ? WHERE id = ?");
$stmt->execute([$filename, $user_id]);

header("Location: ../users/profile_photo?success=Profile photo updated successfully");
exit;
