<?php
/**
 * School Profile Completion Checker
 * Validates and displays school registration progress across all 10 steps
 * Version: 2.2 (Progress: Step N = (N-1)×10%)
 */

// Enable error reporting for debugging (remove in production)
error_reporting(E_ALL);
ini_set('display_errors', 1);

/**
 * Check if a value is empty (considering various data types)
 */
function isFieldEmpty($value) {
    if ($value === null || $value === '') return true;
    if (is_string($value) && trim($value) === '') return true;
    if ($value === '0000-00-00' || $value === '0000') return true;
    if (is_numeric($value) && $value == 0) return false; // 0 is valid for counts
    if (is_string($value) && in_array(strtolower($value), ['yes', 'no', 'y', 'n'])) return false;
    return false;
}

/**
 * Get conditional fields based on decision field value
 */
function getConditionalFieldsForStep($step_name, $decision_field, $decision_value) {
    $conditional_config = [
        'school_land' => [
            'decision_field' => 'land_available',
            'conditions' => [
                'Yes' => ['kanal', 'marla', 'land_type', 'ownership_status', 'land_document'],
                'No' => ['no_land_reason']
            ]
        ],
        'school_building' => [
            'decision_field' => 'building_select',
            'conditions' => [
                'yes' => ['ownershiptype', 'construction_year', 'building_condition', 'cons_material', 'boundry_wall'],
                'no' => ['nobuilding_reason']
            ]
        ],
        'school_smc' => [
            'decision_field' => 'smc_select',
            'conditions' => [
                'yes' => ['smc_active', 'smc_training', 'smc_president_name', 'smc_president_contact', 
                         'smc_bank_account', 'smc_bank_name', 'smc_bank_account_number', 'smc_amount_received'],
                'no' => ['no_smc_reason']
            ]
        ]
    ];
    
    if (isset($conditional_config[$step_name]) && 
        $conditional_config[$step_name]['decision_field'] == $decision_field) {
        $decision_lower = strtolower(trim($decision_value));
        foreach ($conditional_config[$step_name]['conditions'] as $key => $fields) {
            if ($decision_lower === strtolower(trim($key))) {
                return $fields;
            }
        }
    }
    return [];
}

/**
 * Check if specific step is complete
 */
function checkSchoolStepCompletion($conn, $emis_code, $step_number) {
    $step_tables = [
        1 => 'school_profile',
        2 => 'school_land',
        3 => 'school_building',
        4 => 'school_facilities',
        5 => 'school_posts',
        6 => 'school_students',
        7 => 'school_board_results',
        8 => 'school_budget',
        9 => 'school_smc',
        10 => 'school_photos'
    ];
    
    if (!isset($step_tables[$step_number])) {
        return false;
    }
    
    $table_name = $step_tables[$step_number];
    
    try {
        if ($step_number == 1) {
            $stmt = $conn->prepare("SELECT COUNT(*) as count FROM {$table_name} WHERE emis_code = ? AND status = 1");
        } else {
            $stmt = $conn->prepare("SELECT COUNT(*) as count FROM {$table_name} WHERE emis_code = ?");
        }
        
        if ($stmt) {
            $stmt->bind_param("s", $emis_code);
            $stmt->execute();
            $result = $stmt->get_result();
            $row = $result->fetch_assoc();
            $stmt->close();
            return ($row['count'] > 0);
        }
    } catch (Exception $e) {
        error_log("Error checking step $step_number: " . $e->getMessage());
        return false;
    }
    return false;
}

/**
 * Get current step number for school (for navigation)
 */
function getSchoolCurrentStep($conn, $emis_code) {
    $steps = range(1, 10);
    foreach ($steps as $step) {
        if (!checkSchoolStepCompletion($conn, $emis_code, $step)) {
            return $step;
        }
    }
    return 11; // All steps completed
}

/**
 * Main function to check school profile completion
 */
function checkSchoolProfileCompletion($conn, $emis_code) {
    // Step configuration
    $steps = [
        1 => [
            'name' => 'School Profile',
            'table' => 'school_profile',
            'fields' => [
                'school_name', 'school_type', 'school_level', 'school_gender',
                'education_mode', 'school_shift', 'emis_code', 'est_year',
                'established_as', 'district_id', 'tehsil_id', 'constituency_id',
                'union_council_id', 'village', 'post_office', 'locality', 'zone',
                'school_status', 'contact_no', 'whatsapp_no'
            ],
            'condition' => 'status = 1'
        ],
        2 => [
            'name' => 'School Land',
            'table' => 'school_land',
            'decision_field' => 'land_available',
            'min_records' => 1
        ],
        3 => [
            'name' => 'School Building',
            'table' => 'school_building',
            'decision_field' => 'building_select',
            'min_records' => 1
        ],
        4 => [
            'name' => 'School Facilities',
            'table' => 'school_facilities',
            'fields' => [
                'electricity', 'water', 'internet', 'road', 'assembly_ground', 
                'play_ground', 'medical_facility', 'gas_supply', 'public_transport',
                'staff_chairs', 'staff_tables', 'student_desks', 'cupboards', 
                'writing_boards', 'podiums'
            ],
            'min_records' => 1
        ],
        5 => [
            'name' => 'School Posts',
            'table' => 'school_posts',
            'fields' => ['male_staff', 'female_staff', 'budget_posts', 'filled_posts', 'vacant_posts'],
            'min_records' => 1,
            'summary_table' => 'school_posts_summary',
            'summary_key' => 'sp_id'
        ],
        6 => [
            'name' => 'School Students',
            'table' => 'school_students',
            'fields' => [
                'total_male', 'total_female', 'repeating_male', 'repeating_female',
                'orphan_male', 'orphan_female', 'special_male', 'special_female',
                'scholar_male', 'scholar_female'
            ],
            'min_records' => 1,
            'summary_table' => 'school_students_summary',
            'summary_key' => 'ss_id'
        ],
        7 => [
            'name' => 'Board Results',
            'table' => 'school_board_results',
            'fields' => ['session_year', 'class_name', 'total_students', 'total_pass'],
            'min_records' => 0 // Optional
        ],
        8 => [
            'name' => 'School Budget',
            'table' => 'school_budget',
            'fields' => [
                'financial_year_start', 'financial_year_end', 'total_students', 
                'govt_budget', 'budget_expenses'
            ],
            'min_records' => 1,
            'summary_table' => 'school_budget_funds',
            'summary_key' => 'budget_id'
        ],
        9 => [
            'name' => 'School SMC',
            'table' => 'school_smc',
            'decision_field' => 'smc_select',
            'min_records' => 1
        ],
        10 => [
            'name' => 'School Photos',
            'table' => 'school_photos',
            'fields' => ['photo_type', 'file_path', 'photo_hash'],
            'min_records' => 3 // At least 3 photos required
        ]
    ];

    $results = [];
    $completed = 0;
    $total_steps = count($steps);

    foreach ($steps as $step_num => $config) {
        $step_complete = true;
        $missing = [];
        $record_count = 0;
        
        try {
            // Check if table exists
            $table_check = $conn->query("SHOW TABLES LIKE '{$config['table']}'");
            if ($table_check->num_rows == 0) {
                $results[$step_num] = [
                    'completed' => false,
                    'name' => $config['name'],
                    'records' => 0,
                    'missing' => ["Table '{$config['table']}' not found"]
                ];
                continue;
            }
            
            // Build condition
            $where = "WHERE emis_code = ?";
            if (isset($config['condition'])) {
                $where .= " AND {$config['condition']}";
            }
            
            // Get record count
            $stmt = $conn->prepare("SELECT COUNT(*) as count FROM {$config['table']} $where");
            if (!$stmt) {
                throw new Exception("Query prepare failed");
            }
            $stmt->bind_param("s", $emis_code);
            $stmt->execute();
            $count_result = $stmt->get_result();
            $record_count = $count_result->fetch_assoc()['count'];
            $stmt->close();
            
            // Check minimum records
            if (isset($config['min_records']) && $config['min_records'] > 0) {
                if ($record_count < $config['min_records']) {
                    $step_complete = false;
                    $missing[] = "Need {$config['min_records']} record(s), found {$record_count}";
                }
            }
            
            // If records exist, check field completion
            if ($record_count > 0) {
                $stmt = $conn->prepare("SELECT * FROM {$config['table']} $where LIMIT 1");
                $stmt->bind_param("s", $emis_code);
                $stmt->execute();
                $data = $stmt->get_result()->fetch_assoc();
                $stmt->close();
                
                // Handle decision-based fields
                if (isset($config['decision_field']) && isset($data[$config['decision_field']])) {
                    $decision_value = $data[$config['decision_field']];
                    $step_name_key = array_search($step_num, array_keys($steps));
                    $step_name = is_numeric($step_name_key) ? '' : $step_name_key;
                    
                    $conditional_fields = getConditionalFieldsForStep(
                        $config['table'], 
                        $config['decision_field'], 
                        $decision_value
                    );
                    
                    foreach ($conditional_fields as $field) {
                        if (!isset($data[$field]) || isFieldEmpty($data[$field])) {
                            $step_complete = false;
                            $missing[] = $field . ' (required)';
                        }
                    }
                }
                
                // Check regular fields
                if (isset($config['fields'])) {
                    foreach ($config['fields'] as $field) {
                        if (!isset($data[$field]) || isFieldEmpty($data[$field])) {
                            $step_complete = false;
                            $missing[] = $field;
                        }
                    }
                }
                
                // Check summary table
                if (isset($config['summary_table']) && isset($config['summary_key']) && isset($data['id'])) {
                    $summary_stmt = $conn->prepare("SELECT COUNT(*) as count FROM {$config['summary_table']} WHERE {$config['summary_key']} = ?");
                    $summary_stmt->bind_param("i", $data['id']);
                    $summary_stmt->execute();
                    $summary_count = $summary_stmt->get_result()->fetch_assoc()['count'];
                    $summary_stmt->close();
                    
                    if ($summary_count == 0) {
                        $step_complete = false;
                        $missing[] = 'No detail records';
                    }
                }
            } else if (isset($config['min_records']) && $config['min_records'] > 0) {
                $step_complete = false;
                $missing[] = 'No data entered';
            }
            
        } catch (Exception $e) {
            $step_complete = false;
            $missing[] = 'Error: ' . $e->getMessage();
        }
        
        $results[$step_num] = [
            'completed' => $step_complete,
            'name' => $config['name'],
            'records' => $record_count,
            'missing' => $missing
        ];
        
        if ($step_complete) $completed++;
    }
    
    // === MODIFIED PROGRESS CALCULATION ===
    // Progress: Step 1 = 0%, Step 2 = 10%, Step 3 = 20%, ..., Step 11 = 100%
    $current_step = getSchoolCurrentStep($conn, $emis_code);
    $percentage = min(100, ($current_step - 1) * 10);
    
    // Update completed count to match progress display (for UI consistency)
    $completed = min($total_steps, $current_step - 1);
    // =====================================
    
    // Determine status
    $status = 'Incomplete';
    if ($percentage == 100) $status = 'Complete';
    elseif ($percentage >= 80) $status = 'Mostly Complete';
    elseif ($percentage >= 50) $status = 'Partially Complete';
    
    return [
        'percentage' => $percentage,
        'status' => $status,
        'completed' => $completed,
        'total' => $total_steps,
        'emis_code' => $emis_code,
        'steps' => $results,
        'current_step' => $current_step
    ];
}

/**
 * Display progress bar HTML
 */
function displayProgressBar($data) {
    $color = '#e74c3c'; // Red for incomplete
    if ($data['percentage'] >= 100) $color = '#2ecc71'; // Green
    elseif ($data['percentage'] >= 80) $color = '#f39c12'; // Orange
    elseif ($data['percentage'] >= 50) $color = '#3498db'; // Blue
    
    $html = '<div class="profile-completion" style="margin: 20px 0; padding: 20px; background: #f8f9fa; border-radius: 10px; border-left: 5px solid ' . $color . '; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">';
    $html .= '<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">';
    $html .= '<div>';
    $html .= '<h4 style="margin: 0; color: #2c3e50;"><i class="fas fa-school"></i> Registration Progress</h4>';
    $html .= '<p style="margin: 5px 0 0; color: #666;">EMIS: ' . htmlspecialchars($data['emis_code']) . '</p>';
    $html .= '</div>';
    $html .= '<div style="text-align: right;">';
    $html .= '<span style="font-weight: bold; font-size: 1.3em; color: ' . $color . ';">' . $data['percentage'] . '%</span>';
    $html .= '<div style="font-size: 0.9em; color: ' . $color . ';">' . $data['status'] . '</div>';
    $html .= '</div>';
    $html .= '</div>';
    
    // Progress bar
    $html .= '<div style="background: #e0e0e0; border-radius: 10px; height: 20px; overflow: hidden; position: relative;">';
    $html .= '<div style="width: ' . $data['percentage'] . '%; height: 100%; background: ' . $color . '; transition: width 0.5s;"></div>';
    $html .= '</div>';
    
    // Step counters
    $html .= '<div style="margin-top: 10px; text-align: center; color: #666;">';
    $html .= '<strong>' . $data['completed'] . '</strong> of <strong>' . $data['total'] . '</strong> steps completed';
    $html .= '</div>';
    $html .= '</div>';
    
    return $html;
}

/**
 * Display step details
 */
function displayStepDetails($steps) {
    $html = '<div class="step-details" style="margin: 20px 0;">';
    $html .= '<h5 style="color: #2c3e50; margin-bottom: 15px; padding-bottom: 10px; border-bottom: 2px solid #3498db;">';
    $html .= '<i class="fas fa-list"></i> Step-by-Step Status';
    $html .= '</h5>';
    
    foreach ($steps as $num => $step) {
        $icon = $step['completed'] ? 'fa-check-circle' : 'fa-times-circle';
        $color = $step['completed'] ? '#2ecc71' : '#e74c3c';
        $bg = $step['completed'] ? '#f0f9f0' : '#fff0f0';
        
        $html .= '<div style="display: flex; align-items: center; padding: 12px; margin-bottom: 8px; background: ' . $bg . '; border-radius: 6px; border-left: 4px solid ' . $color . ';">';
        $html .= '<div style="background: ' . $color . '; color: white; width: 30px; height: 30px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-weight: bold; margin-right: 15px;">' . $num . '</div>';
        $html .= '<div style="flex: 1;">';
        $html .= '<div style="display: flex; justify-content: space-between;">';
        $html .= '<strong>' . $step['name'] . '</strong>';
        $html .= '<span style="color: ' . $color . ';">' . ($step['completed'] ? 'Complete' : 'Incomplete') . '</span>';
        $html .= '</div>';
        
        if (!$step['completed'] && !empty($step['missing'])) {
            $display = array_slice($step['missing'], 0, 2);
            $html .= '<div style="font-size: 0.85em; color: #e74c3c; margin-top: 5px;">';
            $html .= '<i class="fas fa-exclamation-circle"></i> ' . implode(', ', $display);
            if (count($step['missing']) > 2) {
                $html .= ' (+' . (count($step['missing']) - 2) . ' more)';
            }
            $html .= '</div>';
        }
        
        $html .= '<div style="font-size: 0.8em; color: #999; margin-top: 3px;">Records: ' . $step['records'] . '</div>';
        $html .= '</div>';
        $html .= '<i class="fas ' . $icon . '" style="color: ' . $color . '; font-size: 20px; margin-left: 10px;"></i>';
        $html .= '</div>';
    }
    
    $html .= '</div>';
    return $html;
}

/**
 * Display action required section
 */
function displayActionRequired($steps) {
    $incomplete = array_filter($steps, function($step) {
        return !$step['completed'];
    });
    
    if (empty($incomplete)) {
        return '';
    }
    
    $html = '<div class="action-required" style="margin: 20px 0; padding: 20px; background: linear-gradient(135deg, #fff3cd, #ffeaa7); border-radius: 10px; border-left: 5px solid #ffc107;">';
    $html .= '<h5 style="color: #856404; margin-bottom: 15px;"><i class="fas fa-exclamation-triangle"></i> Action Required</h5>';
    $html .= '<p style="color: #856404; margin-bottom: 15px;">Please complete the following steps:</p>';
    
    foreach ($incomplete as $num => $step) {
        $file = "school_step{$num}.php";
        
        $html .= '<div style="margin-bottom: 10px; padding: 12px; background: rgba(255,255,255,0.7); border-radius: 6px;">';
        $html .= '<div style="display: flex; justify-content: space-between; align-items: center;">';
        $html .= '<div>';
        $html .= '<strong>Step ' . $num . ': ' . $step['name'] . '</strong>';
        if (!empty($step['missing']) && $step['missing'][0] != 'No data entered') {
            $html .= '<div style="font-size: 0.85em; color: #e74c3c;">';
            $html .= count($step['missing']) . ' field(s) need attention';
            $html .= '</div>';
        }
        $html .= '</div>';
        
        $html .= '<a href="' . $file . '" style="background: #3498db; color: white; padding: 8px 16px; border-radius: 4px; text-decoration: none; font-size: 0.9em;">';
        $html .= '<i class="fas fa-edit"></i> Complete';
        $html .= '</a>';
        $html .= '</div>';
        $html .= '</div>';
    }
    
    $html .= '</div>';
    return $html;
}

/**
 * Display completion success message
 */
function displaySuccessMessage($emis_code) {
    $html = '<div class="completion-success" style="margin: 20px 0; padding: 20px; background: linear-gradient(135deg, #d4edda, #c3e6cb); border-radius: 10px; border-left: 5px solid #28a745;">';
    $html .= '<h5 style="color: #155724; margin-bottom: 10px;"><i class="fas fa-check-circle"></i> Profile Complete!</h5>';
    $html .= '<p style="color: #155724; margin-bottom: 15px;">Your school registration is 100% complete and ready for submission.</p>';
    $html .= '<a href="school_dashboard.php?emis_code=' . urlencode($emis_code) . '" style="background: #28a745; color: white; padding: 10px 20px; border-radius: 4px; text-decoration: none; display: inline-block;">';
    $html .= '<i class="fas fa-tachometer-alt"></i> Go to Dashboard';
    $html .= '</a>';
    $html .= '</div>';
    
    return $html;
}

/**
 * Main function to generate complete completion display
 */
function getSchoolCompletionDisplay($conn, $emis_code) {
    if (empty($emis_code)) {
        return '<div class="alert alert-warning">EMIS code not provided</div>';
    }
    
    $data = checkSchoolProfileCompletion($conn, $emis_code);
    
    $output = displayProgressBar($data);
    $output .= displayStepDetails($data['steps']);
    
    if ($data['percentage'] < 100) {
        $output .= displayActionRequired($data['steps']);
    } else {
        $output .= displaySuccessMessage($data['emis_code']);
    }
    
    return $output;
}

/**
 * Generate navigation progress indicator
 */
function getSchoolNavigationProgress($conn, $emis_code, $current_step) {
    if (empty($emis_code)) {
        return '';
    }
    
    $data = checkSchoolProfileCompletion($conn, $emis_code);
    $current_step_name = getStepName($current_step);
    
    // Calculate progress based on current step: Step 1 = 0%, Step 2 = 10%, etc.
    $nav_percentage = min(100, ($current_step - 1) * 10);
    
    $html = '<div class="navigation-progress" style="margin: 20px 0; padding: 15px; background: white; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">';
    $html .= '<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">';
    $html .= '<h5 style="margin: 0; color: #2c3e50;"><i class="fas fa-school"></i> Registration Progress</h5>';
    $html .= '<span style="font-weight: bold; color: #3498db;">Step ' . $current_step . ': ' . $current_step_name . '</span>';
    $html .= '</div>';
    
    // Mini progress bar
    $html .= '<div style="background: #e0e0e0; border-radius: 10px; height: 8px; overflow: hidden; margin-bottom: 10px;">';
    $html .= '<div style="width: ' . $nav_percentage . '%; height: 100%; background: #3498db; transition: width 0.5s;"></div>';
    $html .= '</div>';
    
    $html .= '<div style="text-align: center; color: #666; font-size: 0.9em;">';
    $html .= $data['completed'] . ' of ' . $data['total'] . ' steps completed (' . $nav_percentage . '%)';
    $html .= '</div>';
    $html .= '</div>';
    
    return $html;
}

/**
 * Get step name by number
 */
function getStepName($step_number) {
    $step_names = [
        1 => 'School Profile',
        2 => 'School Land',
        3 => 'School Building',
        4 => 'School Facilities',
        5 => 'School Posts',
        6 => 'School Students',
        7 => 'Board Results',
        8 => 'School Budget',
        9 => 'School SMC',
        10 => 'School Photos'
    ];
    
    return $step_names[$step_number] ?? 'Unknown Step';
}
?>