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

// Check if user is logged in and has admin role
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'admin') {
    $_SESSION['error'] = 'আপনার এই কাজের অনুমতি নেই।';
    header('Location: ../login.php');
    exit();
}

// Get student ID from URL
$student_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($student_id <= 0) {
    $_SESSION['error'] = 'অবৈধ ছাত্র আইডি।';
    header('Location: list.php');
    exit();
}

// Prevent multiple simultaneous deletions
$lock_file = sys_get_temp_dir() . '/student_delete_' . $student_id . '.lock';
if (file_exists($lock_file)) {
    $_SESSION['error'] = 'এই ছাত্রের তথ্য ইতিমধ্যে প্রক্রিয়াধীন।';
    header('Location: list.php');
    exit();
}

// Create lock file
file_put_contents($lock_file, time());

try {
    // Check if student exists
    $stmt = $pdo->prepare("SELECT id, user_id, first_name, last_name, photo FROM students WHERE id = ?");
    $stmt->execute([$student_id]);
    $student = $stmt->fetch();
    
    if (!$student) {
        $_SESSION['error'] = 'ছাত্র খুঁজে পাওয়া যায়নি।';
        header('Location: list.php');
        exit();
    }
    
    $student_name = $student['first_name'] . ' ' . $student['last_name'];
    
    // Disable foreign key checks temporarily for reliable deletion
    $pdo->exec("SET FOREIGN_KEY_CHECKS = 0");
    
    // Start transaction
    $pdo->beginTransaction();
    
    try {
        // Delete photo if exists
        if (!empty($student['photo'])) {
            $photo_path = '../uploads/students/' . $student['photo'];
            if (file_exists($photo_path)) {
                @unlink($photo_path);
            }
        }
        
        // Delete related records manually to ensure they're gone
        $related_tables = [
            'attendance' => 'student_id',
            'results' => 'student_id', 
            'student_subjects' => 'student_id',
            'fees' => 'student_id',
            'fee_payments' => 'fee_id IN (SELECT id FROM fees WHERE student_id = ?)',
            'library_issues' => 'student_id',
            'exam_attendance' => 'student_id',
            'seat_arrangements' => 'student_id'
        ];
        
        foreach ($related_tables as $table => $condition) {
            if ($table === 'fee_payments') {
                // Special case for fee_payments
                $stmt = $pdo->prepare("DELETE FROM fee_payments WHERE fee_id IN (SELECT id FROM fees WHERE student_id = ?)");
                $stmt->execute([$student_id]);
            } else {
                $stmt = $pdo->prepare("DELETE FROM $table WHERE $condition = ?");
                $stmt->execute([$student_id]);
            }
        }
        
        // Delete user account if exists
        if (!empty($student['user_id'])) {
            $stmt = $pdo->prepare("DELETE FROM users WHERE id = ?");
            $stmt->execute([$student['user_id']]);
        }
        
        // Finally delete the student
        $stmt = $pdo->prepare("DELETE FROM students WHERE id = ?");
        $result = $stmt->execute([$student_id]);
        
        if ($result && $stmt->rowCount() > 0) {
            $pdo->commit();
            $_SESSION['success'] = 'ছাত্র "' . $student_name . '" সফলভাবে মুছে ফেলা হয়েছে।';
        } else {
            $pdo->rollBack();
            $_SESSION['error'] = 'ছাত্র মুছে ফেলতে সমস্যা হয়েছে।';
        }
        
    } catch (Exception $e) {
        $pdo->rollBack();
        throw $e;
    }
    
    // Re-enable foreign key checks
    $pdo->exec("SET FOREIGN_KEY_CHECKS = 1");
    
} catch (Exception $e) {
    // Re-enable foreign key checks even on error
    try {
        $pdo->exec("SET FOREIGN_KEY_CHECKS = 1");
    } catch (Exception $ignore) {}
    
    $_SESSION['error'] = 'ছাত্র মুছে ফেলতে ব্যর্থ: ' . $e->getMessage();
} finally {
    // Remove lock file
    if (file_exists($lock_file)) {
        @unlink($lock_file);
    }
}

header('Location: list.php');
exit();
?>