<?php
include 'db_connection.php'; // اگر اتصال دیتابیس جداست

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = isset($_POST['id']) ? intval($_POST['id']) : 0;
    $step = isset($_POST['step']) ? intval($_POST['step']) : 0;

    if ($id > 0 && $step >= 1 && $step <= 10) {
        // حذف فایل گزارش
        if (isset($_POST['delete_report'])) {
                $fileKey = "file" . $step;
                $expertKey = "expert" . $step;
            
                $query = "SELECT `$fileKey` FROM karshenasan WHERE id = $id";
                $result = mysqli_query($conn, $query);
                $row = mysqli_fetch_assoc($result);
            
                if (!empty($row[$fileKey])) {
                    $filePath = 'k_uploads/' . $row[$fileKey];  // مسیر کامل فایل
                    if (file_exists($filePath)) {
                        unlink($filePath);
                    } else {
                        echo "فایل گزارش پیدا نشد! مسیر: $filePath";
                    }
                }
            
                $update = "UPDATE karshenasan SET `$fileKey` = NULL, `$expertKey` = NULL WHERE id = $id";
                if (!mysqli_query($conn, $update)) {
                    echo "خطا در آپدیت دیتابیس: " . mysqli_error($conn);
                }

            }


        // حذف نامه جهاد
        if (isset($_POST['delete_jahad'])) {
            $jahadKey = "jahad" . $step;

            $query = "SELECT `$jahadKey` FROM karshenasan WHERE id = $id";
            $result = mysqli_query($conn, $query);
            $row = mysqli_fetch_assoc($result);

            if (!empty($row[$jahadKey])) {
                $filePath = $row[$jahadKey]; // مثل: k_uploads/jahad/file456.pdf
                if (file_exists($filePath)) {
                    unlink($filePath);
                }
            }

            $update = "UPDATE karshenasan SET `$jahadKey` = NULL WHERE id = $id";
            mysqli_query($conn, $update);
        }
    }
}
?>
