<?php

/**
 * Main configuration file for Birthday Reminder PWA
 * Contains all application settings and constants
 */

// Prevent multiple inclusions
if (defined('CONFIG_LOADED')) {
    return;
}
define('CONFIG_LOADED', true);

// Error reporting (set to 0 in production)
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Timezone - Indian Standard Time (IST)
date_default_timezone_set('Asia/Kolkata');

// Database configuration
if (!defined('DB_HOST')) define('DB_HOST', 'localhost');
if (!defined('DB_NAME')) define('DB_NAME', 'gsagroup_birthday');
if (!defined('DB_USER')) define('DB_USER', 'gsagroup_birthday');
if (!defined('DB_PASS')) define('DB_PASS', 'nK*D([BpImbby=zI');

// Application paths
if (!defined('BASE_PATH')) define('BASE_PATH', dirname(__DIR__));
if (!defined('APP_PATH')) define('APP_PATH', BASE_PATH . '/app');
if (!defined('PUBLIC_PATH')) define('PUBLIC_PATH', BASE_PATH . '/public');
if (!defined('UPLOAD_PATH')) define('UPLOAD_PATH', BASE_PATH . '/uploads');
if (!defined('CONFIG_PATH')) define('CONFIG_PATH', BASE_PATH . '/config');

// Upload directories
if (!defined('IMAGE_UPLOAD_PATH')) define('IMAGE_UPLOAD_PATH', UPLOAD_PATH . '/images');
if (!defined('EXCEL_UPLOAD_PATH')) define('EXCEL_UPLOAD_PATH', UPLOAD_PATH . '/excel');

// URL configuration
// CHANGE ONLY THIS LINE WHEN DEPLOYING - e.g., '/birthday_reminder' or '' for root
// URL configuration
if (!defined('URL_PATH')) define('URL_PATH', '/birthday');

if (!defined('BASE_URL')) define('BASE_URL', 'https://rbtcrm.in' . URL_PATH);
if (!defined('PUBLIC_URL')) define('PUBLIC_URL', BASE_URL . '/public');

// Image processing settings
if (!defined('IMAGE_QUALITY')) define('IMAGE_QUALITY', 80); // WebP quality (0-100)
if (!defined('MAX_IMAGE_SIZE')) define('MAX_IMAGE_SIZE', 5 * 1024 * 1024); // 5MB max file size
if (!defined('ALLOWED_IMAGE_TYPES')) define('ALLOWED_IMAGE_TYPES', ['image/jpeg', 'image/png', 'image/gif', 'image/webp']);

// Excel settings
if (!defined('EXCEL_BATCH_SIZE')) define('EXCEL_BATCH_SIZE', 1000); // Records per Excel file
if (!defined('MAX_EXCEL_SIZE')) define('MAX_EXCEL_SIZE', 10 * 1024 * 1024); // 10MB max file size

// Notification settings
if (!defined('NOTIFICATION_TIME')) define('NOTIFICATION_TIME', '19:26'); // time  4:52 PM IST for daily notifications
if (!defined('NOTIFICATION_TITLE')) define('NOTIFICATION_TITLE', 'Birthday Reminder');
if (!defined('NOTIFICATION_MESSAGE')) define('NOTIFICATION_MESSAGE', 'Don\'t forget to wish your loved ones today! 🎉');

// VAPID keys for push notifications (generate using config/generate_vapid_keys.php)
// These are placeholder keys - generate real ones for production
if (!defined('VAPID_PUBLIC_KEY')) define('VAPID_PUBLIC_KEY', 'BEl62iUYgUivxIkv69yViEuiBIa-Ib9-SkvMeAtA3LFgDzkrxZJjSgSnfckjBJuBkr3qBUYIHBQFLXYp5Nksh8U');
if (!defined('VAPID_PRIVATE_KEY')) define('VAPID_PRIVATE_KEY', 'UUxI4O8-FbRouAevSmBQ6o18hgE4nSG3qwvJTfKc-ls');
if (!defined('VAPID_SUBJECT')) define('VAPID_SUBJECT', 'mailto:admin@example.com');

// Session settings - persistent until manual logout
if (!defined('SESSION_LIFETIME')) define('SESSION_LIFETIME', 0); // 0 = until browser closes, but we'll keep session data indefinitely
if (!defined('SESSION_NAME')) define('SESSION_NAME', 'birthday_reminder_session');

// Security settings
if (!defined('CSRF_TOKEN_NAME')) define('CSRF_TOKEN_NAME', 'csrf_token');
if (!defined('PASSWORD_MIN_LENGTH')) define('PASSWORD_MIN_LENGTH', 6);

// Pagination settings
if (!defined('ITEMS_PER_PAGE')) define('ITEMS_PER_PAGE', 20);

// Application settings
if (!defined('APP_NAME')) define('APP_NAME', 'Birthday Reminder PWA');
if (!defined('APP_VERSION')) define('APP_VERSION', '1.0.0');

// Error logging
if (!defined('LOG_PATH')) define('LOG_PATH', BASE_PATH . '/logs');
if (!defined('ERROR_LOG_FILE')) define('ERROR_LOG_FILE', LOG_PATH . '/error.log');

// Create logs directory if it doesn't exist
if (!file_exists(LOG_PATH)) {
    mkdir(LOG_PATH, 0755, true);
}

// Set custom error log
ini_set('error_log', ERROR_LOG_FILE);

// Create upload directories if they don't exist
$uploadDirs = [IMAGE_UPLOAD_PATH, EXCEL_UPLOAD_PATH];
foreach ($uploadDirs as $dir) {
    if (!file_exists($dir)) {
        mkdir($dir, 0755, true);
    }
}



// Load Composer autoload
if (file_exists(BASE_PATH . '/vendor/autoload.php')) {
    require_once BASE_PATH . '/vendor/autoload.php';
}

// Load database class
require_once CONFIG_PATH . '/Database.php';

/**
 * Helper function to get database instance
 */
if (!function_exists('db')) {
    function db()
    {
        return Database::getInstance();
    }
}

/**
 * Helper function to check if user is authenticated
 */
if (!function_exists('isAuthenticated')) {
    function isAuthenticated()
    {
        return isset($_SESSION['user_id']) && !empty($_SESSION['user_id']);
    }
}

/**
 * Helper function to get current user ID
 */
if (!function_exists('getCurrentUserId')) {
    function getCurrentUserId()
    {
        return $_SESSION['user_id'] ?? null;
    }
}

/**
 * Helper function to get current user type
 */
if (!function_exists('getCurrentUserType')) {
    function getCurrentUserType()
    {
        return $_SESSION['user_type'] ?? 'user';
    }
}

/**
 * Helper function to check if current user is admin
 */
if (!function_exists('isAdmin')) {
    function isAdmin()
    {
        // Check if user_type exists in session (for backward compatibility)
        if (!isset($_SESSION['user_type'])) {
            return false; // Default to non-admin if user_type not set
        }
        return $_SESSION['user_type'] === 'admin';
    }
}

/**
 * Helper function to redirect
 */
if (!function_exists('redirect')) {
    function redirect($url)
    {
        header("Location: $url");
        exit;
    }
}

/**
 * Helper function to sanitize input
 */
if (!function_exists('sanitize')) {
    function sanitize($data)
    {
        if (is_array($data)) {
            return array_map('sanitize', $data);
        }
        return htmlspecialchars(strip_tags(trim($data)), ENT_QUOTES, 'UTF-8');
    }
}

/**
 * Helper function to generate CSRF token
 */
if (!function_exists('generateCsrfToken')) {
    function generateCsrfToken()
    {
        if (!isset($_SESSION[CSRF_TOKEN_NAME])) {
            $_SESSION[CSRF_TOKEN_NAME] = bin2hex(random_bytes(32));
        }
        return $_SESSION[CSRF_TOKEN_NAME];
    }
}

/**
 * Helper function to verify CSRF token
 */
if (!function_exists('verifyCsrfToken')) {
    function verifyCsrfToken($token)
    {
        return isset($_SESSION[CSRF_TOKEN_NAME]) && hash_equals($_SESSION[CSRF_TOKEN_NAME], $token);
    }
}

/**
 * Helper function to format date for display
 */
if (!function_exists('formatDate')) {
    function formatDate($date, $format = 'd-m-Y')
    {
        if (empty($date)) return '';
        $dateObj = new DateTime($date);
        return $dateObj->format($format);
    }
}

/**
 * Helper function to format datetime for display
 */
if (!function_exists('formatDateTime')) {
    function formatDateTime($datetime, $format = 'd-m-Y H:i:s')
    {
        if (empty($datetime)) return '';
        $dateObj = new DateTime($datetime);
        return $dateObj->format($format);
    }
}

/**
 * Helper function to get today's date
 */
if (!function_exists('getToday')) {
    function getToday()
    {
        return date('Y-m-d');
    }
}

/**
 * Helper function to check if today is a birthday
 */
if (!function_exists('isBirthdayToday')) {
    function isBirthdayToday($dateOfBirth)
    {
        $today = new DateTime();
        $dob = new DateTime($dateOfBirth);

        return $today->format('m-d') === $dob->format('m-d');
    }
}

/**
 * Helper function to log errors
 */
if (!function_exists('logError')) {
    function logError($message, $context = [])
    {
        $logMessage = date('Y-m-d H:i:s') . ' - ' . $message;
        if (!empty($context)) {
            $logMessage .= ' | Context: ' . json_encode($context);
        }
        error_log($logMessage . PHP_EOL, 3, ERROR_LOG_FILE);
    }
}

/**
 * Helper function to send JSON response
 */
if (!function_exists('jsonResponse')) {
    function jsonResponse($data, $statusCode = 200)
    {
        http_response_code($statusCode);
        header('Content-Type: application/json');
        echo json_encode($data);
        exit;
    }
}

/**
 * Helper function to send error JSON response
 */
if (!function_exists('jsonError')) {
    function jsonError($message, $code = 'ERROR', $statusCode = 400, $details = null)
    {
        $response = [
            'success' => false,
            'error' => [
                'code' => $code,
                'message' => $message
            ]
        ];

        if ($details !== null) {
            $response['error']['details'] = $details;
        }

        jsonResponse($response, $statusCode);
    }
}

/**
 * Helper function to send success JSON response
 */
if (!function_exists('jsonSuccess')) {
    function jsonSuccess($data = [], $message = 'Success')
    {
        jsonResponse([
            'success' => true,
            'message' => $message,
            'data' => $data
        ], 200);
    }
}
