<?php
// db.php - database credentials, PDO connection, debug log toggle
// This file must be included first by every page (before functions.php).

date_default_timezone_set('Asia/Kolkata');

// APPROOT: absolute path to the project root. db.php always lives in the root itself
// (root pages do `require 'db.php'`, /api pages do `require '../db.php'`), so resolving
// this once here - regardless of which script included the file - keeps log file paths
// correct from both locations without needing __DIR__ anywhere else in the project.
define('APPROOT', dirname(__FILE__));

// ---- Debug logging toggle ----
// Set to 1 to write all PHP errors + logDebug() calls to /logs/debug.log, 0 to disable.
define('DEBUGLOG', 1);
define('DEBUGLOGFILE', APPROOT . '/logs/debug.log');
define('OTPLOGFILE', APPROOT . '/logs/otp_log.txt');

if (DEBUGLOG) {
    ini_set('display_errors', 0);
    ini_set('log_errors', 1);
    ini_set('error_log', DEBUGLOGFILE);
    error_reporting(E_ALL);
} else {
    ini_set('display_errors', 0);
    error_reporting(0);
}

// ---- DB credentials ----
define('DBHOST', 'localhost:4306');
define('DBNAME', 'divar');
define('DBUSER', 'root');
define('DBPASS', 'password');

// ---- Razorpay credentials ----
// Replace with live/test keys from Razorpay Dashboard > Settings > API Keys
define('RAZORPAYKEYID', 'rzp_test_xxxxxxxxxxxx');
define('RAZORPAYKEYSECRET', 'xxxxxxxxxxxxxxxxxxxxxxxx');
// Webhook secret set in Razorpay Dashboard > Settings > Webhooks
define('RAZORPAYWEBHOOKSECRET', 'xxxxxxxxxxxxxxxxxxxxxxxx');

// ---- SMS Gateway credentials (Fabcoders) ----
define('SMSAPIKEY', '3139636f64616e746f736d733130301751399255');
define('SMSSENDERID', 'FABCOD');
define('SMSTEMPLATEID', '1207172524581229915');

try {
    $pdo = new PDO(
        'mysql:host=' . DBHOST . ';dbname=' . DBNAME . ';charset=utf8mb4',
        DBUSER,
        DBPASS,
        [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES => false,
        ]
    );
    // Keep MySQL session in IST to match PHP
    $pdo->exec("SET time_zone = '+05:30'");
} catch (PDOException $e) {
    if (DEBUGLOG) {
        error_log('[DB CONNECTION ERROR] ' . $e->getMessage());
    }
    http_response_code(500);
    die('Database connection failed. Please try again later.');
}
