<?php
/**
 * Salary Register Test & Debug Page
 * Access: http://localhost/hrm2/test_salary_register.php
 */

error_reporting(E_ALL);
ini_set('display_errors', 1);

echo "<h1>🔧 Salary Register Debug & Test</h1>";
echo "<style>body{font-family:Arial;padding:20px;} .success{color:green;} .error{color:red;} .info{color:blue;} pre{background:#f5f5f5;padding:10px;border-radius:5px;}</style>";

// Test 1: Database Connection
echo "<h2>Test 1: Database Connection</h2>";
try {
    $db = new PDO('mysql:host=localhost;dbname=hrm2;charset=utf8mb4', 'root', '');
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "<p class='success'>✅ Database connection successful!</p>";
} catch (Exception $e) {
    echo "<p class='error'>❌ Database connection failed: " . $e->getMessage() . "</p>";
    die();
}

// Test 2: Check if table exists
echo "<h2>Test 2: Table Existence</h2>";
try {
    $stmt = $db->query("SHOW TABLES LIKE 'salary_register'");
    if ($stmt->rowCount() > 0) {
        echo "<p class='success'>✅ Table 'salary_register' exists!</p>";
        
        // Show table structure
        $columns = $db->query("DESCRIBE salary_register");
        $columnList = $columns->fetchAll(PDO::FETCH_ASSOC);
        echo "<p class='info'>📋 Table has " . count($columnList) . " columns</p>";
        echo "<details><summary>View Column Details</summary><pre>";
        print_r($columnList);
        echo "</pre></details>";
    } else {
        echo "<p class='error'>❌ Table 'salary_register' does NOT exist!</p>";
        echo "<p>Creating table now...</p>";
        
        // Create table
        $createSQL = "
        CREATE TABLE IF NOT EXISTS salary_register (
            register_id INT AUTO_INCREMENT PRIMARY KEY,
            site_id INT NOT NULL,
            month VARCHAR(50) NOT NULL,
            employee_name VARCHAR(255) NOT NULL,
            designation VARCHAR(100),
            employee_type VARCHAR(50) DEFAULT 'FTC',
            category VARCHAR(50) DEFAULT 'Skilled',
            status VARCHAR(20) DEFAULT 'Active',
            basic_employer DECIMAL(10,2) DEFAULT 0,
            vda DECIMAL(10,2) DEFAULT 0,
            special_allowance DECIMAL(10,2) DEFAULT 0,
            other_allowance_employer DECIMAL(10,2) DEFAULT 0,
            hra_employer DECIMAL(10,2) DEFAULT 0,
            days_present INT DEFAULT 0,
            days_absent INT DEFAULT 0,
            weekly_off INT DEFAULT 0,
            pay_days INT DEFAULT 0,
            basic_earned DECIMAL(10,2) DEFAULT 0,
            hra_earned DECIMAL(10,2) DEFAULT 0,
            other_allowance_earned DECIMAL(10,2) DEFAULT 0,
            spl_allowance DECIMAL(10,2) DEFAULT 0,
            pf DECIMAL(10,2) DEFAULT 0,
            esi DECIMAL(10,2) DEFAULT 0,
            pt DECIMAL(10,2) DEFAULT 0,
            pf_rebill DECIMAL(10,2) DEFAULT 0,
            esic_rebill DECIMAL(10,2) DEFAULT 0,
            leave_amount DECIMAL(10,2) DEFAULT 0,
            holiday DECIMAL(10,2) DEFAULT 0,
            bonus DECIMAL(10,2) DEFAULT 0,
            uniform DECIMAL(10,2) DEFAULT 0,
            gratuity DECIMAL(10,2) DEFAULT 0,
            food_allowance DECIMAL(10,2) DEFAULT 0,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            KEY idx_site_month (site_id, month),
            KEY idx_employee (employee_name)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ";
        
        $db->exec($createSQL);
        echo "<p class='success'>✅ Table created successfully!</p>";
    }
} catch (Exception $e) {
    echo "<p class='error'>❌ Error checking/creating table: " . $e->getMessage() . "</p>";
}

// Test 3: Test Insert
echo "<h2>Test 3: Test Data Insert</h2>";
try {
    $testData = [
        'site_id' => 1,
        'month' => 'Test ' . date('F Y'),
        'employee_name' => 'Test Employee ' . date('His'),
        'designation' => 'Test Position',
        'employee_type' => 'FTC',
        'category' => 'Skilled',
        'status' => 'Active',
        'basic_employer' => 15000.00,
        'basic_earned' => 12000.00,
        'pf' => 1440.00,
        'days_present' => 25
    ];
    
    $stmt = $db->prepare("
        INSERT INTO salary_register (
            site_id, month, employee_name, designation, employee_type, category, status,
            basic_employer, basic_earned, pf, days_present
        ) VALUES (
            :site_id, :month, :employee_name, :designation, :employee_type, :category, :status,
            :basic_employer, :basic_earned, :pf, :days_present
        )
    ");
    
    $stmt->execute($testData);
    $insertId = $db->lastInsertId();
    
    echo "<p class='success'>✅ Test insert successful! Record ID: {$insertId}</p>";
    echo "<details><summary>View Inserted Data</summary><pre>";
    print_r($testData);
    echo "</pre></details>";
    
} catch (Exception $e) {
    echo "<p class='error'>❌ Test insert failed: " . $e->getMessage() . "</p>";
}

// Test 4: Count records
echo "<h2>Test 4: Database Records</h2>";
try {
    $count = $db->query("SELECT COUNT(*) FROM salary_register")->fetchColumn();
    echo "<p class='info'>📊 Total records in database: <strong>{$count}</strong></p>";
    
    if ($count > 0) {
        echo "<details><summary>View Last 5 Records</summary>";
        $records = $db->query("
            SELECT register_id, employee_name, designation, month, basic_employer, created_at 
            FROM salary_register 
            ORDER BY register_id DESC 
            LIMIT 5
        ")->fetchAll(PDO::FETCH_ASSOC);
        
        echo "<table border='1' cellpadding='5' style='border-collapse:collapse;'>";
        echo "<tr><th>ID</th><th>Name</th><th>Designation</th><th>Month</th><th>Basic</th><th>Created</th></tr>";
        foreach ($records as $record) {
            echo "<tr>";
            echo "<td>{$record['register_id']}</td>";
            echo "<td>{$record['employee_name']}</td>";
            echo "<td>{$record['designation']}</td>";
            echo "<td>{$record['month']}</td>";
            echo "<td>" . number_format($record['basic_employer'], 2) . "</td>";
            echo "<td>{$record['created_at']}</td>";
            echo "</tr>";
        }
        echo "</table>";
        echo "</details>";
    }
} catch (Exception $e) {
    echo "<p class='error'>❌ Error counting records: " . $e->getMessage() . "</p>";
}

// Test 5: PHP Info
echo "<h2>Test 5: PHP Configuration</h2>";
echo "<p class='info'>PHP Version: <strong>" . phpversion() . "</strong></p>";
echo "<p class='info'>PDO Drivers: <strong>" . implode(', ', PDO::getAvailableDrivers()) . "</strong></p>";

// Test 6: File Permissions
echo "<h2>Test 6: File Check</h2>";
$files = [
    'modules/payroll/salary_register.php',
    'SALARY_REGISTER_SETUP.sql',
    'database/migrations/create_salary_register_table.sql'
];

foreach ($files as $file) {
    $path = __DIR__ . '/' . $file;
    if (file_exists($path)) {
        echo "<p class='success'>✅ {$file} - EXISTS</p>";
    } else {
        echo "<p class='error'>❌ {$file} - NOT FOUND</p>";
    }
}

echo "<hr>";
echo "<h2>🎯 Summary</h2>";
echo "<p><strong>If all tests pass:</strong></p>";
echo "<ul>";
echo "<li>✅ Database is working</li>";
echo "<li>✅ Table exists</li>";
echo "<li>✅ Inserts are working</li>";
echo "<li>✅ System is ready!</li>";
echo "</ul>";

echo "<p><a href='modules/payroll/salary_register.php' style='display:inline-block;padding:10px 20px;background:#4CAF50;color:white;text-decoration:none;border-radius:5px;'>🚀 Go to Salary Register</a></p>";
?>
