<?php
/**
 * Database Configuration for GST Notes Module
 * Uses the main project's database configuration
 */

// Use main project's database settings (extracted from database.php)
// Since we can't directly include CodeIgniter's database.php due to BASEPATH check,
// we'll use the same configuration values
$db_config = [
    'host' => 'localhost',
    'username' => 'uzrs_vinayaga_traders',
    'password' => 'uzrs_vinayaga_traders',
    'database' => 'uzrs_vinayaga_traders',
    'charset' => 'utf8mb4'
];

// Enable exceptions for mysqli so we can return clean JSON errors in endpoints
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
    $mysqli = new mysqli(
        $db_config['host'],
        $db_config['username'],
        $db_config['password'],
        $db_config['database']
    );
    $mysqli->set_charset($db_config['charset']);
} catch (Throwable $e) {
    // Re-throw as RuntimeException to be caught by callers (AJAX endpoints)
    throw new RuntimeException('Database connection error: ' . $e->getMessage(), 0, $e);
}

// Global functions for common operations
function executeQuery($query, $params = []) {
    global $mysqli;
    if (!isset($mysqli)) {
        throw new RuntimeException('Database handle not initialized');
    }
    $stmt = $mysqli->prepare($query);
    if (!$stmt) {
        throw new RuntimeException('Prepare failed: ' . $mysqli->error);
    }
    if ($params) {
        // Derive parameter types (i=int, d=double, s=string, b=blob)
        $types = '';
        foreach ($params as $p) {
            if (is_int($p)) $types .= 'i';
            elseif (is_float($p)) $types .= 'd';
            elseif (is_null($p)) { $types .= 's'; } // NULL bound as string then converted
            else $types .= 's';
        }
        $stmt->bind_param($types, ...$params);
    }
    if (!$stmt->execute()) {
        throw new RuntimeException('Execute failed: ' . $stmt->error);
    }
    return $stmt;
}

function fetchAll($query, $params = []) {
    $stmt = executeQuery($query, $params);
    $result = $stmt->get_result();
    return $result ? $result->fetch_all(MYSQLI_ASSOC) : [];
}

function fetchOne($query, $params = []) {
    $stmt = executeQuery($query, $params);
    $result = $stmt->get_result();
    return $result ? $result->fetch_assoc() : null;
}

function getLastInsertId() {
    global $mysqli;
    return $mysqli->insert_id;
}

// Generate next note number
function generateNoteNumber($type) {
    $prefix = ($type === 'credit') ? 'CN' : 'DN';
    $year = date('Y');
    
    $table = $type . '_notes';
    $query = "SELECT MAX(CAST(SUBSTRING(note_number, -3) AS UNSIGNED)) as max_num 
              FROM $table 
              WHERE note_number LIKE '$prefix-$year-%'";
    
    $result = fetchOne($query);
    $next_num = ($result['max_num'] ?? 0) + 1;
    
    return $prefix . '-' . $year . '-' . str_pad($next_num, 3, '0', STR_PAD_LEFT);
}

// Calculate GST amounts
function calculateGST($taxable_amount, $cgst_rate = 0, $sgst_rate = 0, $igst_rate = 0) {
    $cgst_amount = ($taxable_amount * $cgst_rate) / 100;
    $sgst_amount = ($taxable_amount * $sgst_rate) / 100;
    $igst_amount = ($taxable_amount * $igst_rate) / 100;
    $total_amount = $taxable_amount + $cgst_amount + $sgst_amount + $igst_amount;
    
    return [
        'cgst_amount' => round($cgst_amount, 2),
        'sgst_amount' => round($sgst_amount, 2),
        'igst_amount' => round($igst_amount, 2),
        'total_amount' => round($total_amount, 2)
    ];
}
?>
