<?php
declare(strict_types=1);
session_start();
require_once '../../config.php';
header('Content-Type: application/json');
if (!isset($_SESSION['user_id'])) { http_response_code(401); echo json_encode(['success'=>false]); exit; }
$conn = getDBConnection();
if (!$conn instanceof mysqli) { echo json_encode(['success'=>false]); exit; }
$id = (int) ($_POST['id'] ?? 0);
$stmt = $conn->prepare("SELECT stored_filename FROM ai_study_materials WHERE id = ? AND uploaded_by = ? LIMIT 1");
$stmt->bind_param('ii', $id, $_SESSION['user_id']);
$stmt->execute();
$row = $stmt->get_result()->fetch_assoc();
$stmt->close();
if (!$row) { echo json_encode(['success'=>false, 'message'=>'Material not found']); exit; }
$path = rtrim(EXAM_UPLOAD_DIR, '/\\') . DIRECTORY_SEPARATOR . (string) $row['stored_filename'];
if (is_file($path)) { @unlink($path); }
$delete = $conn->prepare("DELETE FROM ai_study_materials WHERE id = ? AND uploaded_by = ?");
$delete->bind_param('ii', $id, $_SESSION['user_id']);
$delete->execute();
$delete->close();
echo json_encode(['success'=>true]);
