<?php
require_once("../includes/session.php");
require_once("../includes/config.php");
checkSession();

if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_FILES['profile_pic'])) {
    $user_id = $udata['id'];
    $file = $_FILES['profile_pic'];
    
    // Validate file
    $allowed = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
    $filename = $file['name'];
    $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
    
    if(!in_array($ext, $allowed)) {
        header("Location: profile.php?error=Invalid file type. Only JPG, PNG, GIF allowed.");
        exit;
    }
    
    if($file['size'] > 5000000) { // 5MB limit
        header("Location: profile.php?error=File too large. Max 5MB allowed.");
        exit;
    }
    
    // Create profiles directory if not exists
    $uploadDir = "../admin/uploads/profiles/";
    if(!is_dir($uploadDir)) {
        mkdir($uploadDir, 0755, true);
    }
    
    // Generate unique filename
    $newFilename = "user_" . $user_id . "_" . time() . "." . $ext;
    $targetPath = $uploadDir . $newFilename;
    
    // Delete old profile pic if exists
    if(!empty($udata['profile_pic']) && file_exists($uploadDir . $udata['profile_pic'])) {
        unlink($uploadDir . $udata['profile_pic']);
    }
    
    // Move uploaded file
    if(move_uploaded_file($file['tmp_name'], $targetPath)) {
        // Update database
        $stmt = mysqli_prepare($ahk_conn, "UPDATE users SET profile_pic = ? WHERE id = ?");
        mysqli_stmt_bind_param($stmt, "si", $newFilename, $user_id);
        
        if(mysqli_stmt_execute($stmt)) {
            header("Location: profile.php?success=Profile picture updated successfully!");
        } else {
            header("Location: profile.php?error=Database error. Please try again.");
        }
        mysqli_stmt_close($stmt);
    } else {
        header("Location: profile.php?error=Failed to upload file. Please try again.");
    }
} else {
    header("Location: profile.php");
}
exit;
?>