<?php
session_start();
require_once '../config/database.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: ../login.php');
    exit();
}

$user_role = $_SESSION['user_role'];
$user_id = $_SESSION['user_id'];

// Get file ID
$file_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($file_id <= 0) {
    header('Location: my_files.php?error=invalid_id');
    exit();
}

// Get user info based on role
$user_info = null;
if ($user_role == 'student') {
    $stmt = $pdo->prepare("SELECT * FROM students WHERE user_id = ?");
    $stmt->execute([$user_id]);
    $user_info = $stmt->fetch();
} elseif ($user_role == 'teacher') {
    $stmt = $pdo->prepare("SELECT * FROM teachers WHERE user_id = ?");
    $stmt->execute([$user_id]);
    $user_info = $stmt->fetch();
}

// Get file information
$stmt = $pdo->prepare("
    SELECT * FROM file_uploads 
    WHERE id = ? AND uploader_type = ? AND uploader_id = ? AND status = 'active'
");
$stmt->execute([$file_id, $user_role, $user_info ? $user_info['id'] : 0]);
$file = $stmt->fetch();

if (!$file) {
    header('Location: my_files.php?error=file_not_found');
    exit();
}

try {
    $pdo->beginTransaction();
    
    // Mark file as deleted in database
    $stmt = $pdo->prepare("UPDATE file_uploads SET status = 'deleted' WHERE id = ?");
    $stmt->execute([$file_id]);
    
    // Delete physical file
    $file_path = '../' . $file['file_path'];
    if (file_exists($file_path)) {
        unlink($file_path);
    }
    
    $pdo->commit();
    
    header('Location: my_files.php?success=file_deleted');
    exit();
    
} catch (Exception $e) {
    $pdo->rollBack();
    header('Location: my_files.php?error=delete_failed');
    exit();
}
?>