<?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 "<h2>ইনভয়েজ সিস্টেম সেটআপ</h2>";

try {
    // Create fee_payments table
    $sql = "
    CREATE TABLE IF NOT EXISTS fee_payments (
        id INT AUTO_INCREMENT PRIMARY KEY,
        fee_id INT NOT NULL,
        amount DECIMAL(10,2) NOT NULL,
        payment_date DATETIME NOT NULL,
        payment_method VARCHAR(50) DEFAULT 'cash',
        transaction_id VARCHAR(100) NULL,
        notes TEXT NULL,
        created_by INT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        
        INDEX idx_fee_id (fee_id),
        INDEX idx_payment_date (payment_date),
        INDEX idx_payment_method (payment_method)
    )";
    
    $pdo->exec($sql);
    echo "<p>✅ fee_payments টেবিল তৈরি হয়েছে</p>";
    
    // Check if sample data exists
    $count = $pdo->query("SELECT COUNT(*) FROM fee_payments")->fetchColumn();
    echo "<p>বর্তমানে fee_payments টেবিলে $count টি রেকর্ড আছে</p>";
    
    if ($count == 0) {
        // Insert sample payment data
        $sql = "
        INSERT INTO fee_payments (fee_id, amount, payment_date, payment_method, transaction_id, notes, created_by)
        SELECT 
            f.id,
            f.paid_amount,
            DATE_ADD(f.created_at, INTERVAL FLOOR(RAND() * 30) DAY),
            CASE 
                WHEN RAND() < 0.5 THEN 'cash'
                WHEN RAND() < 0.8 THEN 'bank_transfer'
                ELSE 'mobile_banking'
            END,
            CONCAT('TXN-', DATE_FORMAT(f.created_at, '%Y%m%d'), '-', f.id),
            CASE 
                WHEN f.fee_type LIKE '%বেতন%' THEN 'মাসিক বেতন পরিশোধ'
                WHEN f.fee_type LIKE '%পরীক্ষা%' THEN 'পরীক্ষা ফি পরিশোধ'
                ELSE 'ফি পরিশোধ'
            END,
            1
        FROM fees f 
        WHERE f.paid_amount > 0 
        LIMIT 100";
        
        $stmt = $pdo->prepare($sql);
        $stmt->execute();
        $inserted = $stmt->rowCount();
        echo "<p>✅ $inserted টি নমুনা পেমেন্ট রেকর্ড যোগ করা হয়েছে</p>";
        
        // Update transaction IDs for variety
        $pdo->exec("
            UPDATE fee_payments 
            SET transaction_id = CONCAT('BANK-', DATE_FORMAT(payment_date, '%Y%m%d'), '-', id)
            WHERE payment_method = 'bank_transfer'
        ");
        
        $pdo->exec("
            UPDATE fee_payments 
            SET transaction_id = CONCAT('MOBILE-', DATE_FORMAT(payment_date, '%Y%m%d'), '-', id)
            WHERE payment_method = 'mobile_banking'
        ");
        
        echo "<p>✅ ট্রানজেকশন আইডি আপডেট করা হয়েছে</p>";
    }
    
    // Show some sample data
    echo "<h3>নমুনা পেমেন্ট রেকর্ড:</h3>";
    $samples = $pdo->query("
        SELECT 
            fp.*,
            f.fee_type,
            s.first_name,
            s.last_name,
            s.roll_number
        FROM fee_payments fp
        JOIN fees f ON fp.fee_id = f.id
        JOIN students s ON f.student_id = s.id
        ORDER BY fp.payment_date DESC
        LIMIT 10
    ")->fetchAll();
    
    if (!empty($samples)) {
        echo "<table border='1' style='border-collapse: collapse; width: 100%;'>";
        echo "<tr><th>পেমেন্ট ID</th><th>শিক্ষার্থী</th><th>ফি টাইপ</th><th>পরিমাণ</th><th>তারিখ</th><th>পদ্ধতি</th><th>ট্রানজেকশন ID</th></tr>";
        
        foreach ($samples as $payment) {
            echo "<tr>";
            echo "<td>" . $payment['id'] . "</td>";
            echo "<td>" . $payment['first_name'] . " " . $payment['last_name'] . " (রোল: " . $payment['roll_number'] . ")</td>";
            echo "<td>" . $payment['fee_type'] . "</td>";
            echo "<td>৳" . number_format($payment['amount'], 2) . "</td>";
            echo "<td>" . date('d/m/Y H:i', strtotime($payment['payment_date'])) . "</td>";
            echo "<td>" . $payment['payment_method'] . "</td>";
            echo "<td>" . $payment['transaction_id'] . "</td>";
            echo "</tr>";
        }
        echo "</table>";
    }
    
    echo "<br><h3>✅ ইনভয়েজ সিস্টেম সেটআপ সম্পন্ন!</h3>";
    echo "<p><a href='invoice.php' class='btn btn-primary'>ইনভয়েজ পেজে যান</a></p>";
    
} catch (Exception $e) {
    echo "<p style='color: red;'>❌ ত্রুটি: " . $e->getMessage() . "</p>";
}
?>