<?php
/**
 * Database Configuration & Connection (PDO)
 * Ghalla Mandi ERP — naveed_trader_db
 */

// Set Pakistan timezone (PKT = UTC+5) for all date() calls
date_default_timezone_set('Asia/Karachi');

class Database {
    private static $instance = null;

    // Database credentials
    private const HOST = 'localhost';
    private const DB_NAME = 'cortexby_naveed_trader';
    private const USERNAME = 'cortexby_naveed_trader';
    private const PASSWORD = '(8Ss;22.7%EhD=8u';
    private const CHARSET = 'utf8mb4';

    // JWT Secret Key (Change in production!)
    public const JWT_SECRET = 'NaveedTrader_GhallaMandi_2026_SecretKey!@#$';
    public const JWT_EXPIRY = 86400; // 24 hours in seconds

    /**
     * Get PDO connection (Singleton)
     */
    public static function connect(): PDO {
        if (self::$instance === null) {
            try {
                $dsn = "mysql:host=" . self::HOST . ";dbname=" . self::DB_NAME . ";charset=" . self::CHARSET;
                
                self::$instance = new PDO($dsn, self::USERNAME, self::PASSWORD, [
                    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
                    PDO::ATTR_DEFAULT_FETCH_MODE  => PDO::FETCH_ASSOC,
                    PDO::ATTR_EMULATE_PREPARES    => false,
                    PDO::MYSQL_ATTR_INIT_COMMAND  => "SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci, time_zone = '+05:00'"
                ]);
            } catch (PDOException $e) {
                http_response_code(500);
                echo json_encode([
                    'success' => false,
                    'message' => 'Database connection failed: ' . $e->getMessage()
                ]);
                exit;
            }
        }
        return self::$instance;
    }
}