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

// Set response header
header('Content-Type: application/json');

// Log the request
error_log("=== DELETE ROUTINE REQUEST START ===");
error_log("Delete routine request received: " . print_r($_POST, true));
error_log("Session data: " . print_r($_SESSION, true));
error_log("Request method: " . ($_SERVER['REQUEST_METHOD'] ?? 'Unknown'));
error_log("Content type: " . ($_SERVER['CONTENT_TYPE'] ?? 'Not set'));
error_log("Request URI: " . ($_SERVER['REQUEST_URI'] ?? 'Not set'));

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    error_log("UNAUTHORIZED: User not logged in");
    error_log("=== DELETE ROUTINE REQUEST END ===");
    echo json_encode(['success' => false, 'message' => 'অননুমোদিত অ্যাক্সেস']);
    exit();
}

error_log("AUTHORIZED: User ID " . $_SESSION['user_id'] . ", Role: " . ($_SESSION['user_role'] ?? 'Not set'));

// Check if it's a POST request
if ($_SERVER['REQUEST_METHOD'] != 'POST') {
    error_log("INVALID METHOD: " . $_SERVER['REQUEST_METHOD']);
    error_log("=== DELETE ROUTINE REQUEST END ===");
    echo json_encode(['success' => false, 'message' => 'অবৈধ অনুরোধ']);
    exit();
}

try {
    $pdo->beginTransaction();
    
    // Check if we're deleting multiple routines
    if (isset($_POST['ids'])) {
        error_log("BULK DELETE: Processing IDs " . $_POST['ids']);
        // Bulk delete
        $ids = explode(',', $_POST['ids']);
        $ids = array_map('intval', $ids);
        $ids = array_filter($ids, function($id) { return $id > 0; });
        $force_delete = isset($_POST['force']) && $_POST['force'] == '1';
        
        if (empty($ids)) {
            error_log("INVALID IDS: Empty or invalid IDs provided");
            throw new Exception('অবৈধ রুটিন আইডি');
        }
        
        error_log("VALID IDS: " . implode(', ', $ids) . ", Force Delete: " . ($force_delete ? 'Yes' : 'No'));
        
        // Prepare placeholders for IN clause
        $placeholders = str_repeat('?,', count($ids) - 1) . '?';
        
        try {
            // Delete results first (due to foreign key constraints)
            error_log("DELETING RESULTS for IDs: " . implode(', ', $ids));
            $stmt = $pdo->prepare("DELETE FROM results WHERE exam_id IN ($placeholders)");
            $stmt->execute($ids);
            error_log("DELETED RESULTS: " . $stmt->rowCount() . " records");
            
            // Delete exam questions
            error_log("DELETING EXAM QUESTIONS for IDs: " . implode(', ', $ids));
            $stmt = $pdo->prepare("DELETE FROM exam_questions WHERE exam_id IN ($placeholders)");
            $stmt->execute($ids);
            error_log("DELETED EXAM QUESTIONS: " . $stmt->rowCount() . " records");
            
            // Delete seat arrangements
            error_log("DELETING SEAT ARRANGEMENTS for IDs: " . implode(', ', $ids));
            $stmt = $pdo->prepare("DELETE FROM seat_arrangements WHERE exam_id IN ($placeholders)");
            $stmt->execute($ids);
            error_log("DELETED SEAT ARRANGEMENTS: " . $stmt->rowCount() . " records");
            
            // Delete exam subjects for all selected exams
            error_log("DELETING EXAM SUBJECTS for IDs: " . implode(', ', $ids));
            $stmt = $pdo->prepare("DELETE FROM exam_subjects WHERE exam_id IN ($placeholders)");
            $stmt->execute($ids);
            error_log("DELETED EXAM SUBJECTS: " . $stmt->rowCount() . " records");
            
            // Check if there are any remaining references
            $placeholders_check = str_repeat('?,', count($ids) - 1) . '?';
            $stmt = $pdo->prepare("SELECT exam_id, COUNT(*) as count FROM exam_subjects WHERE exam_id IN ($placeholders_check) GROUP BY exam_id");
            $stmt->execute($ids);
            $remaining = $stmt->fetchAll();
            error_log("REMAINING EXAM SUBJECTS: " . print_r($remaining, true));
            
            // If force delete is enabled, clean up any orphaned records
            if ($force_delete) {
                error_log("FORCE DELETE ENABLED FOR BULK: Cleaning up related tables");
                
                // Clean up any related attendance records
                $stmt = $pdo->prepare("DELETE FROM exam_attendance WHERE exam_id IN ($placeholders)");
                $stmt->execute($ids);
                error_log("CLEANED UP EXAM ATTENDANCE: " . $stmt->rowCount() . " records");
                
                // Clean up any related room duties
                $stmt = $pdo->prepare("DELETE FROM exam_room_duties WHERE exam_id IN ($placeholders)");
                $stmt->execute($ids);
                error_log("CLEANED UP EXAM ROOM DUTIES: " . $stmt->rowCount() . " records");
                
                // Clean up any related rooms
                $stmt = $pdo->prepare("DELETE FROM exam_rooms WHERE exam_id IN ($placeholders)");
                $stmt->execute($ids);
                error_log("CLEANED UP EXAM ROOMS: " . $stmt->rowCount() . " records");
            }
            
            // Delete the exams themselves
            error_log("DELETING EXAMS for IDs: " . implode(', ', $ids));
            $stmt = $pdo->prepare("DELETE FROM exams WHERE id IN ($placeholders)");
            $stmt->execute($ids);
            error_log("DELETED EXAMS: " . $stmt->rowCount() . " records");
            
            $pdo->commit();
            
            $message = count($ids) . 'টি পরীক্ষার রুটিন সফলভাবে মুছে ফেলা হয়েছে';
            error_log("SUCCESS: " . $message);
            error_log("=== DELETE ROUTINE REQUEST END ===");
            echo json_encode(['success' => true, 'message' => $message]);
            
        } catch (Exception $e) {
            // If regular delete fails and force delete is requested, try a more aggressive approach
            if (!$force_delete) {
                throw $e; // Re-throw if not force delete
            }
            
            error_log("REGULAR BULK DELETE FAILED, TRYING FORCE DELETE: " . $e->getMessage());
            
            // Try to disable foreign key checks temporarily (be very careful with this!)
            $pdo->exec("SET FOREIGN_KEY_CHECKS = 0");
            
            try {
                // Aggressive cleanup
                $tables_to_clean = [
                    'exam_attendance',
                    'exam_room_duties',
                    'exam_rooms',
                    'exam_subjects',
                    'results',
                    'exam_questions',
                    'seat_arrangements'
                ];
                
                foreach ($tables_to_clean as $table) {
                    $stmt = $pdo->prepare("DELETE FROM `$table` WHERE exam_id IN ($placeholders)");
                    $stmt->execute($ids);
                    error_log("FORCE CLEANED $table: " . $stmt->rowCount() . " records");
                }
                
                // Finally delete the exams
                $stmt = $pdo->prepare("DELETE FROM exams WHERE id IN ($placeholders)");
                $stmt->execute($ids);
                error_log("FORCE DELETED EXAMS: " . $stmt->rowCount() . " records");
                
                // Re-enable foreign key checks
                $pdo->exec("SET FOREIGN_KEY_CHECKS = 1");
                
                $pdo->commit();
                
                $message = count($ids) . 'টি পরীক্ষার রুটিন জোর করে মুছে ফেলা হয়েছে';
                error_log("FORCE BULK DELETE SUCCESS: " . $message);
                error_log("=== DELETE ROUTINE REQUEST END ===");
                echo json_encode(['success' => true, 'message' => $message]);
                
            } catch (Exception $force_e) {
                // Re-enable foreign key checks even if force delete fails
                $pdo->exec("SET FOREIGN_KEY_CHECKS = 1");
                throw $force_e;
            }
        }
        
    } else if (isset($_POST['id'])) {
        error_log("SINGLE DELETE: Processing ID " . $_POST['id']);
        // Single delete
        $routine_id = (int)$_POST['id'];
        $force_delete = isset($_POST['force']) && $_POST['force'] == '1';
        
        if ($routine_id <= 0) {
            error_log("INVALID ID: " . $routine_id);
            throw new Exception('অবৈধ রুটিন আইডি');
        }
        
        error_log("VALID ID: " . $routine_id . ", Force Delete: " . ($force_delete ? 'Yes' : 'No'));
        
        try {
            // Delete results first (due to foreign key constraints)
            error_log("DELETING RESULTS for ID: " . $routine_id);
            $stmt = $pdo->prepare("DELETE FROM results WHERE exam_id = ?");
            $stmt->execute([$routine_id]);
            error_log("DELETED RESULTS: " . $stmt->rowCount() . " records");
            
            // Delete exam questions
            error_log("DELETING EXAM QUESTIONS for ID: " . $routine_id);
            $stmt = $pdo->prepare("DELETE FROM exam_questions WHERE exam_id = ?");
            $stmt->execute([$routine_id]);
            error_log("DELETED EXAM QUESTIONS: " . $stmt->rowCount() . " records");
            
            // Delete seat arrangements
            error_log("DELETING SEAT ARRANGEMENTS for ID: " . $routine_id);
            $stmt = $pdo->prepare("DELETE FROM seat_arrangements WHERE exam_id = ?");
            $stmt->execute([$routine_id]);
            error_log("DELETED SEAT ARRANGEMENTS: " . $stmt->rowCount() . " records");
            
            // First delete all exam subjects associated with this exam
            error_log("DELETING EXAM SUBJECTS for ID: " . $routine_id);
            $stmt = $pdo->prepare("DELETE FROM exam_subjects WHERE exam_id = ?");
            $stmt->execute([$routine_id]);
            error_log("DELETED EXAM SUBJECTS: " . $stmt->rowCount() . " records");
            
            // Check if there are any remaining references
            $stmt = $pdo->prepare("SELECT COUNT(*) FROM exam_subjects WHERE exam_id = ?");
            $stmt->execute([$routine_id]);
            $remaining = $stmt->fetchColumn();
            error_log("REMAINING EXAM SUBJECTS: " . $remaining . " records");
            
            // If force delete is enabled, clean up any orphaned records
            if ($force_delete) {
                error_log("FORCE DELETE ENABLED: Cleaning up related tables");
                
                // Clean up any related attendance records
                $stmt = $pdo->prepare("DELETE FROM exam_attendance WHERE exam_id = ?");
                $stmt->execute([$routine_id]);
                error_log("CLEANED UP EXAM ATTENDANCE: " . $stmt->rowCount() . " records");
                
                // Clean up any related room duties
                $stmt = $pdo->prepare("DELETE FROM exam_room_duties WHERE exam_id = ?");
                $stmt->execute([$routine_id]);
                error_log("CLEANED UP EXAM ROOM DUTIES: " . $stmt->rowCount() . " records");
                
                // Clean up any related rooms
                $stmt = $pdo->prepare("DELETE FROM exam_rooms WHERE exam_id = ?");
                $stmt->execute([$routine_id]);
                error_log("CLEANED UP EXAM ROOMS: " . $stmt->rowCount() . " records");
            }
            
            // Then delete the exam routine itself
            error_log("DELETING EXAM for ID: " . $routine_id);
            $stmt = $pdo->prepare("DELETE FROM exams WHERE id = ?");
            $stmt->execute([$routine_id]);
            error_log("DELETED EXAM: " . $stmt->rowCount() . " records");
            
            $pdo->commit();
            
            $message = 'পরীক্ষার রুটিন সফলভাবে মুছে ফেলা হয়েছে';
            error_log("SUCCESS: " . $message);
            error_log("=== DELETE ROUTINE REQUEST END ===");
            echo json_encode(['success' => true, 'message' => $message]);
            
        } catch (Exception $e) {
            // If regular delete fails and force delete is requested, try a more aggressive approach
            if (!$force_delete) {
                throw $e; // Re-throw if not force delete
            }
            
            error_log("REGULAR DELETE FAILED, TRYING FORCE DELETE: " . $e->getMessage());
            
            // Try to disable foreign key checks temporarily (be very careful with this!)
            $pdo->exec("SET FOREIGN_KEY_CHECKS = 0");
            
            try {
                // Aggressive cleanup
                $tables_to_clean = [
                    'exam_attendance',
                    'exam_room_duties',
                    'exam_rooms',
                    'exam_subjects',
                    'results',
                    'exam_questions',
                    'seat_arrangements'
                ];
                
                foreach ($tables_to_clean as $table) {
                    $stmt = $pdo->prepare("DELETE FROM `$table` WHERE exam_id = ?");
                    $stmt->execute([$routine_id]);
                    error_log("FORCE CLEANED $table: " . $stmt->rowCount() . " records");
                }
                
                // Finally delete the exam
                $stmt = $pdo->prepare("DELETE FROM exams WHERE id = ?");
                $stmt->execute([$routine_id]);
                error_log("FORCE DELETED EXAM: " . $stmt->rowCount() . " records");
                
                // Re-enable foreign key checks
                $pdo->exec("SET FOREIGN_KEY_CHECKS = 1");
                
                $pdo->commit();
                
                $message = 'পরীক্ষার রুটিন জোর করে মুছে ফেলা হয়েছে';
                error_log("FORCE DELETE SUCCESS: " . $message);
                error_log("=== DELETE ROUTINE REQUEST END ===");
                echo json_encode(['success' => true, 'message' => $message]);
                
            } catch (Exception $force_e) {
                // Re-enable foreign key checks even if force delete fails
                $pdo->exec("SET FOREIGN_KEY_CHECKS = 1");
                throw $force_e;
            }
        }
        
    } else {
        error_log("INVALID PARAMETERS: " . print_r($_POST, true));
        throw new Exception('অবৈধ অনুরোধ');
    }
    
} catch (Exception $e) {
    $pdo->rollBack();
    error_log("ERROR: " . $e->getMessage());
    error_log("=== DELETE ROUTINE REQUEST END ===");
    echo json_encode(['success' => false, 'message' => 'মুছে ফেলতে ত্রুটি: ' . $e->getMessage()]);
}
?>