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

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

echo "<!DOCTYPE html>
<html lang='bn'>
<head>
    <meta charset='UTF-8'>
    <meta name='viewport' content='width=device-width, initial-scale=1.0'>
    <title>Fix Missing Individual Passing Marks</title>
    <link href='https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css' rel='stylesheet'>
    <link href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css' rel='stylesheet'>
</head>
<body class='bg-light'>
    <div class='container mt-5'>
        <div class='row justify-content-center'>
            <div class='col-md-10'>
                <div class='card'>
                    <div class='card-header bg-primary text-white'>
                        <h4><i class='fas fa-tools'></i> Fix Missing Individual Passing Marks</h4>
                    </div>
                    <div class='card-body'>";

try {
    $pdo->beginTransaction();
    
    echo "<h5><i class='fas fa-search'></i> Checking for missing individual passing marks...</h5>";
    
    // Fix subject_mark_distribution table
    echo "<h6>1. Fixing subject_mark_distribution table:</h6>";
    
    $stmt = $pdo->query("
        SELECT * FROM subject_mark_distribution 
        WHERE (cq_pass_marks IS NULL OR cq_pass_marks = 0) 
           OR (mcq_pass_marks IS NULL OR mcq_pass_marks = 0) 
           OR (practical_pass_marks IS NULL OR practical_pass_marks = 0)
    ");
    
    $missing_distributions = $stmt->fetchAll();
    $fixed_count = 0;
    
    foreach ($missing_distributions as $dist) {
        $updates = [];
        $params = [];
        
        // Set CQ passing marks if missing and CQ marks > 0
        if (($dist['cq_pass_marks'] === null || $dist['cq_pass_marks'] == 0) && $dist['cq_marks'] > 0) {
            $cq_pass = round($dist['cq_marks'] * 0.4, 2); // 40% of CQ marks
            $updates[] = "cq_pass_marks = ?";
            $params[] = $cq_pass;
            echo "<p class='text-info'>Setting CQ pass marks for ID {$dist['id']}: {$cq_pass}</p>";
        }
        
        // Set MCQ passing marks if missing and MCQ marks > 0
        if (($dist['mcq_pass_marks'] === null || $dist['mcq_pass_marks'] == 0) && $dist['mcq_marks'] > 0) {
            $mcq_pass = round($dist['mcq_marks'] * 0.4, 2); // 40% of MCQ marks
            $updates[] = "mcq_pass_marks = ?";
            $params[] = $mcq_pass;
            echo "<p class='text-info'>Setting MCQ pass marks for ID {$dist['id']}: {$mcq_pass}</p>";
        }
        
        // Set Practical passing marks if missing and Practical marks > 0
        if (($dist['practical_pass_marks'] === null || $dist['practical_pass_marks'] == 0) && $dist['practical_marks'] > 0) {
            $practical_pass = round($dist['practical_marks'] * 0.4, 2); // 40% of Practical marks
            $updates[] = "practical_pass_marks = ?";
            $params[] = $practical_pass;
            echo "<p class='text-info'>Setting Practical pass marks for ID {$dist['id']}: {$practical_pass}</p>";
        }
        
        if (!empty($updates)) {
            $params[] = $dist['id'];
            $update_sql = "UPDATE subject_mark_distribution SET " . implode(', ', $updates) . " WHERE id = ?";
            $update_stmt = $pdo->prepare($update_sql);
            $update_stmt->execute($params);
            $fixed_count++;
        }
    }
    
    echo "<p class='text-success'><strong>✅ subject_mark_distribution: {$fixed_count} records updated</strong></p>";
    
    // Fix mark_distributions table
    echo "<h6>2. Fixing mark_distributions table:</h6>";
    
    $stmt2 = $pdo->query("
        SELECT * FROM mark_distributions 
        WHERE (cq_pass_marks IS NULL OR cq_pass_marks = 0) 
           OR (mcq_pass_marks IS NULL OR mcq_pass_marks = 0) 
           OR (practical_pass_marks IS NULL OR practical_pass_marks = 0)
    ");
    
    $missing_distributions2 = $stmt2->fetchAll();
    $fixed_count2 = 0;
    
    foreach ($missing_distributions2 as $dist) {
        $updates = [];
        $params = [];
        
        // Set CQ passing marks if missing and CQ marks > 0
        if (($dist['cq_pass_marks'] === null || $dist['cq_pass_marks'] == 0) && $dist['cq_marks'] > 0) {
            $cq_pass = round($dist['cq_marks'] * 0.4, 2); // 40% of CQ marks
            $updates[] = "cq_pass_marks = ?";
            $params[] = $cq_pass;
            echo "<p class='text-info'>Setting CQ pass marks for ID {$dist['id']}: {$cq_pass}</p>";
        }
        
        // Set MCQ passing marks if missing and MCQ marks > 0
        if (($dist['mcq_pass_marks'] === null || $dist['mcq_pass_marks'] == 0) && $dist['mcq_marks'] > 0) {
            $mcq_pass = round($dist['mcq_marks'] * 0.4, 2); // 40% of MCQ marks
            $updates[] = "mcq_pass_marks = ?";
            $params[] = $mcq_pass;
            echo "<p class='text-info'>Setting MCQ pass marks for ID {$dist['id']}: {$mcq_pass}</p>";
        }
        
        // Set Practical passing marks if missing and Practical marks > 0
        if (($dist['practical_pass_marks'] === null || $dist['practical_pass_marks'] == 0) && $dist['practical_marks'] > 0) {
            $practical_pass = round($dist['practical_marks'] * 0.4, 2); // 40% of Practical marks
            $updates[] = "practical_pass_marks = ?";
            $params[] = $practical_pass;
            echo "<p class='text-info'>Setting Practical pass marks for ID {$dist['id']}: {$practical_pass}</p>";
        }
        
        if (!empty($updates)) {
            $params[] = $dist['id'];
            $update_sql = "UPDATE mark_distributions SET " . implode(', ', $updates) . " WHERE id = ?";
            $update_stmt = $pdo->prepare($update_sql);
            $update_stmt->execute($params);
            $fixed_count2++;
        }
    }
    
    echo "<p class='text-success'><strong>✅ mark_distributions: {$fixed_count2} records updated</strong></p>";
    
    $pdo->commit();
    
    echo "<div class='alert alert-success mt-4'>";
    echo "<h5><i class='fas fa-check-circle'></i> সফলভাবে সম্পন্ন!</h5>";
    echo "<p><strong>মোট আপডেট:</strong> " . ($fixed_count + $fixed_count2) . " টি record</p>";
    echo "<ul>";
    echo "<li>subject_mark_distribution: {$fixed_count} টি record</li>";
    echo "<li>mark_distributions: {$fixed_count2} টি record</li>";
    echo "</ul>";
    echo "<p><strong>এখন সব mark distributions এ individual passing marks (CQ, MCQ, Practical) সেট করা আছে।</strong></p>";
    echo "<p>Individual passing marks = Component marks এর 40%</p>";
    echo "</div>";
    
    // Show verification
    echo "<h5><i class='fas fa-check'></i> Verification:</h5>";
    
    $verify_stmt = $pdo->query("
        SELECT COUNT(*) as total,
               SUM(CASE WHEN cq_pass_marks > 0 THEN 1 ELSE 0 END) as cq_set,
               SUM(CASE WHEN mcq_pass_marks > 0 THEN 1 ELSE 0 END) as mcq_set,
               SUM(CASE WHEN practical_pass_marks > 0 THEN 1 ELSE 0 END) as practical_set
        FROM subject_mark_distribution
    ");
    $verify_result = $verify_stmt->fetch();
    
    echo "<div class='alert alert-info'>";
    echo "<strong>subject_mark_distribution table:</strong><br>";
    echo "Total records: {$verify_result['total']}<br>";
    echo "CQ passing marks set: {$verify_result['cq_set']}<br>";
    echo "MCQ passing marks set: {$verify_result['mcq_set']}<br>";
    echo "Practical passing marks set: {$verify_result['practical_set']}<br>";
    echo "</div>";
    
    $verify_stmt2 = $pdo->query("
        SELECT COUNT(*) as total,
               SUM(CASE WHEN cq_pass_marks > 0 THEN 1 ELSE 0 END) as cq_set,
               SUM(CASE WHEN mcq_pass_marks > 0 THEN 1 ELSE 0 END) as mcq_set,
               SUM(CASE WHEN practical_pass_marks > 0 THEN 1 ELSE 0 END) as practical_set
        FROM mark_distributions
    ");
    $verify_result2 = $verify_stmt2->fetch();
    
    echo "<div class='alert alert-info'>";
    echo "<strong>mark_distributions table:</strong><br>";
    echo "Total records: {$verify_result2['total']}<br>";
    echo "CQ passing marks set: {$verify_result2['cq_set']}<br>";
    echo "MCQ passing marks set: {$verify_result2['mcq_set']}<br>";
    echo "Practical passing marks set: {$verify_result2['practical_set']}<br>";
    echo "</div>";
    
} catch (Exception $e) {
    $pdo->rollBack();
    echo "<div class='alert alert-danger'>";
    echo "<h5><i class='fas fa-exclamation-triangle'></i> ত্রুটি!</h5>";
    echo "<p>আপডেট করতে সমস্যা হয়েছে: " . $e->getMessage() . "</p>";
    echo "</div>";
}

echo "                    </div>
                    <div class='card-footer'>
                        <a href='marks/entry.php' class='btn btn-primary'>
                            <i class='fas fa-edit'></i> মার্কস এন্ট্রিতে যান
                        </a>
                        <a href='debug_individual_passing.php' class='btn btn-info'>
                            <i class='fas fa-bug'></i> Debug আবার চালান
                        </a>
                        <a href='index.php' class='btn btn-secondary'>
                            <i class='fas fa-home'></i> হোমে ফিরুন
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>";
?>