<?php
// config.example.php
// Copy this file to config.php and fill in your actual credentials.
// NEVER commit config.php to version control!

// Session cookie hardening — must be set before session_start() in any file
ini_set('session.cookie_httponly', 1);
ini_set('session.cookie_samesite', 'Lax');
// Uncomment the line below if site is served over HTTPS:
// ini_set('session.cookie_secure', 1);

// Database Configuration
define('DB_HOST', 'localhost');
define('DB_NAME', 'sanibook_vol1');
define('DB_USER', 'your_db_user_here');
define('DB_PASS', 'your_db_password_here');

// SMTP Configuration
define('SMTP_HOST', 'your_smtp_host_here');
define('SMTP_USER', 'your_smtp_user_here');
define('SMTP_PASS', 'your_smtp_password_here');
define('SMTP_PORT', 587);
define('SMTP_FROM_EMAIL', 'no-reply@yourdomain.com');
define('SMTP_FROM_NAME', 'SaniBook Registry');

// ----------------------------------------------------------------------
// DATABASE CONNECTION
// ----------------------------------------------------------------------
// Enable error reporting for debugging
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Prevent MySQLi from throwing Exceptions
mysqli_report(MYSQLI_REPORT_OFF);

$conn = null;
try {
    if (!class_exists('mysqli')) {
        throw new Exception("MySQLi extension not installed/enabled.");
    }
    $conn = @new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
    if ($conn->connect_error) {
        throw new Exception("Connection failed: " . $conn->connect_error);
    }
} catch (Exception $e) {
    error_log("Database connection failed: " . $e->getMessage());
    $conn = null;
}

// ----------------------------------------------------------------------
// TOKEN SYSTEM CONFIGURATION (Dynamic from Database)
// ----------------------------------------------------------------------
$token_costs = [
    'token_cost_per_char' => 1,
    'token_cost_per_image' => 2500,
    'token_cost_per_video_sec' => 100,
    'token_cost_per_audio_sec' => 10,
    'token_cost_per_extra_category' => 3500,
    'token_cost_base_value' => 1,
    'token_cost_editing' => 0
];

if ($conn) {
    $cost_query = $conn->query("SELECT setting_key, setting_value FROM settings WHERE setting_key LIKE 'token_cost_%'");
    if ($cost_query) {
        while ($row = $cost_query->fetch_assoc()) {
            $token_costs[$row['setting_key']] = $row['setting_value'];
        }
    }
}

define('COST_PER_CHAR', floatval($token_costs['token_cost_per_char']));
define('COST_PER_IMAGE', intval($token_costs['token_cost_per_image']));
define('COST_PER_VIDEO_SEC', intval($token_costs['token_cost_per_video_sec']));
define('COST_PER_AUDIO_SEC', intval($token_costs['token_cost_per_audio_sec']));
define('COST_PER_EXTRA_CATEGORY', intval($token_costs['token_cost_per_extra_category']));
define('COST_BASE_VALUE', floatval($token_costs['token_cost_base_value']));
define('COST_EDITING', intval($token_costs['token_cost_editing']));

// SECURE FILE STORAGE PATH
define('SECURE_UPLOAD_PATH', __DIR__ . '/../SaniBook_Uploads_Secure/');

// MOCK MODE CONFIGURATION
define('MOCK_MODE', false);

// ----------------------------------------------------------------------
// SECURITY HELPERS
// ----------------------------------------------------------------------
if (!function_exists('sanitize_text_field')) {
    function sanitize_text_field(?string $str): string
    {
        if ($str === null)
            return '';
        return htmlspecialchars(strip_tags(trim($str)), ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('esc_html')) {
    function esc_html(?string $str): string
    {
        if ($str === null)
            return '';
        return htmlspecialchars($str, ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('esc_attr')) {
    function esc_attr(?string $str): string
    {
        if ($str === null)
            return '';
        return htmlspecialchars($str, ENT_QUOTES, 'UTF-8');
    }
}

// ----------------------------------------------------------------------
// HELPER FUNCTIONS FOR STATS
// ----------------------------------------------------------------------

function get_submission_count($column, $value, $partial = false)
{
    global $conn;
    if (!$conn)
        return 0;

    try {
        if ($partial) {
            $sql = "SELECT COUNT(*) FROM submissions WHERE $column LIKE ? AND is_verified = 1";
            $search = "%" . $value . "%";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("s", $search);
        } else {
            $sql = "SELECT COUNT(*) FROM submissions WHERE $column = ? AND is_verified = 1";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("s", $value);
        }

        if ($stmt->execute()) {
            $count = 0;
            $stmt->bind_result($count);
            $stmt->fetch();
            $stmt->close();
            return $count;
        }
    } catch (Exception $e) {
        return 0;
    }
    return 0;
}

function get_submissions_by_filter($column, $value, $limit = 10, $partial = false)
{
    global $conn;
    if (!$conn)
        return [];

    $data = [];
    try {
        if ($partial) {
            $sql = "SELECT id, org_name, title, data, created_at FROM submissions WHERE $column LIKE ? AND is_verified = 1 ORDER BY created_at DESC LIMIT ?";
            $search = "%" . $value . "%";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("si", $search, $limit);
        } else {
            $sql = "SELECT id, org_name, title, data, created_at FROM submissions WHERE $column = ? AND is_verified = 1 ORDER BY created_at DESC LIMIT ?";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("si", $value, $limit);
        }

        if ($stmt->execute()) {
            $result = $stmt->get_result();
            while ($row = $result->fetch_assoc()) {
                $data[] = $row;
            }
            $stmt->close();
        }
    } catch (Exception $e) {
        return [];
    }
    return $data;
}

function get_pillar_count($type)
{
    global $conn;
    if (!$conn)
        return 0;

    $pillar_map = [
        'financing' => 'Financing',
        'governance' => 'Governance',
        'research' => 'Research & Learning',
        'collaboration' => 'Collaboration',
        'mhm' => 'Menstrual Health Management',
        'capacity-building' => 'Capacity Building',
    ];

    $pillar_name = $pillar_map[$type] ?? null;
    if (!$pillar_name)
        return 0;

    $explicit_count = 0;
    $sql_explicit = "SELECT COUNT(*) FROM submissions WHERE is_verified = 1 AND enabling_pillars LIKE ?";
    $like_val = '%"' . $pillar_name . '"%';
    try {
        $stmt = $conn->prepare($sql_explicit);
        if ($stmt) {
            $stmt->bind_param("s", $like_val);
            $stmt->execute();
            $row = $stmt->get_result()->fetch_row();
            $explicit_count = (int) $row[0];
            $stmt->close();
        }
    } catch (Exception $e) {
        // fallthrough
    }

    $legacy_count = 0;
    $sql_legacy = "SELECT COUNT(*) FROM submissions WHERE is_verified = 1 AND (enabling_pillars IS NULL OR enabling_pillars = '[]') AND ";
    switch ($type) {
        case 'financing':
            $sql_legacy .= "(role = 'Private Sector' OR data LIKE '%finance%' OR data LIKE '%fund%' OR data LIKE '%invest%')";
            break;
        case 'governance':
            $sql_legacy .= "(role = 'Government' OR data LIKE '%policy%' OR data LIKE '%regulat%' OR data LIKE '%law%')";
            break;
        case 'research':
            $sql_legacy .= "(role = 'Academia' OR data LIKE '%research%' OR data LIKE '%data%' OR data LIKE '%evidence%')";
            break;
        case 'collaboration':
            $sql_legacy .= "(role = 'Civil Society' OR data LIKE '%partnership%' OR data LIKE '%coordinate%' OR data LIKE '%network%')";
            break;
        case 'mhm':
            $sql_legacy .= "(title LIKE '%menstrual%' OR data LIKE '%menstrual%' OR data LIKE '%period%' OR data LIKE '%hygiene%')";
            break;
    }

    try {
        $result = $conn->query($sql_legacy);
        if ($result) {
            $row = $result->fetch_row();
            $legacy_count = (int) $row[0];
        }
    } catch (Exception $e) {
        // fallthrough
    }

    return $explicit_count + $legacy_count;
}

function get_category_stats($id)
{
    $stats = get_detailed_category_stats($id);
    return ($stats['story'] + $stats['chronicles']) . " Listings";
}

function get_detailed_category_stats($id)
{
    global $conn;
    $stats = ['story' => 0, 'chronicles' => 0];

    if (!$conn)
        return $stats;

    $stmt = $conn->prepare("SELECT COUNT(*) FROM content WHERE category_id = ? AND type = 'story' AND status = 'approved'");
    if ($stmt) {
        $stmt->bind_param("i", $id);
        if ($stmt->execute()) {
            $stmt->bind_result($count);
            if ($stmt->fetch())
                $stats['story'] = $count;
        }
        $stmt->close();
    }

    $stmt = $conn->prepare("SELECT COUNT(*) FROM content WHERE category_id = ? AND type = 'chronicle' AND status = 'approved'");
    if ($stmt) {
        $stmt->bind_param("i", $id);
        if ($stmt->execute()) {
            $stmt->bind_result($count);
            if ($stmt->fetch())
                $stats['chronicles'] = $count;
        }
        $stmt->close();
    }

    return $stats;
}

// ----------------------------------------------------------------------
// GOOGLE RECAPTCHA CONFIGURATION
// ----------------------------------------------------------------------
$settings = [];
if ($conn) {
    $s_query = $conn->query("SELECT setting_key, setting_value FROM settings");
    if ($s_query) {
        while ($row = $s_query->fetch_assoc()) {
            $settings[$row['setting_key']] = $row['setting_value'];
        }
    }
}

define('RECAPTCHA_SITE_KEY', $settings['recaptcha_site_key'] ?? 'your_recaptcha_site_key_here');
define('RECAPTCHA_SECRET_KEY', $settings['recaptcha_secret_key'] ?? 'your_recaptcha_secret_key_here');

// SMTP Constants (Override defaults if set in DB)
if (!empty($settings['smtp_host']))
    define('SMTP_HOST_DB', $settings['smtp_host']);
if (!empty($settings['smtp_port']))
    define('SMTP_PORT_DB', $settings['smtp_port']);
if (!empty($settings['smtp_user']))
    define('SMTP_USER_DB', $settings['smtp_user']);
if (!empty($settings['smtp_pass']))
    define('SMTP_PASS_DB', $settings['smtp_pass']);

// Google OAuth Configuration
define('GOOGLE_OAUTH_ENABLED', true);
define('GOOGLE_CLIENT_ID', $settings['google_client_id'] ?? '');
define('GOOGLE_CLIENT_SECRET', $settings['google_client_secret'] ?? '');
define('GOOGLE_REDIRECT_URI', $settings['google_redirect_uri'] ?? '');

?>
