<?php
// ============================================
// MeeVakeel - Configuration File
// ============================================

define('SITE_NAME', 'MeeVakeel');
// define('SITE_URL', 'http://localhost/nyaya-guru');
define('SITE_URL', 'http://localhost/Mobeentaj/MeeVakeel/');
define('SITE_EMAIL', 'info@meevakeel.in');
define('SITE_PHONE', '+91 9876543210');
define('SITE_WHATSAPP', '9876543210');
define('ADMIN_EMAIL', 'admin@nyayaguru.in');

// Database Configuration
define('DB_HOST', 'localhost');
define('DB_NAME', 'nyaya_guru');
define('DB_USER', 'root');
define('DB_PASS', '');
define('DB_CHARSET', 'utf8mb4');

// Razorpay
define('RAZORPAY_KEY_ID', 'rzp_test_XXXXXX');
define('RAZORPAY_KEY_SECRET', 'XXXXXX');
define('PLATFORM_COMMISSION_PERCENT', 20);

// File Upload
define('UPLOAD_DIR', dirname(__DIR__) . '/assets/uploads/');
define('UPLOAD_URL', SITE_URL . '/assets/uploads/');
define('MAX_FILE_SIZE', 5 * 1024 * 1024); // 5MB
define('ALLOWED_IMAGE_TYPES', ['image/jpeg', 'image/png', 'image/gif', 'image/webp']);
define('ALLOWED_DOC_TYPES', ['application/pdf', 'image/jpeg', 'image/png']);

// Session
define('SESSION_NAME', 'nyaya_guru_session');
define('SESSION_LIFETIME', 86400); // 24 hours

// OTP
define('OTP_EXPIRY_MINUTES', 10);

// SMTP
define('SMTP_HOST', 'smtp.gmail.com');
define('SMTP_PORT', 587);
define('SMTP_USERNAME', 'noreply@nyayaguru.in');
define('SMTP_PASSWORD', 'your_smtp_password');
define('SMTP_FROM_NAME', 'MeeVakeel');

// SMS (MSG91)
define('MSG91_AUTH_KEY', 'your_msg91_key');
define('MSG91_SENDER_ID', 'NYAGRU');

// Timezone
date_default_timezone_set('Asia/Kolkata');

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

// Start Session
if (session_status() === PHP_SESSION_NONE) {
    session_name(SESSION_NAME);
    session_start();
}

// ============================================
// DATABASE CONNECTION
// ============================================
function getDB() {
    static $pdo = null;
    if ($pdo === null) {
        try {
            $dsn = "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=" . DB_CHARSET;
            $options = [
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                PDO::ATTR_EMULATE_PREPARES => false,
            ];
            $pdo = new PDO($dsn, DB_USER, DB_PASS, $options);
        } catch (PDOException $e) {
            die(json_encode(['error' => 'Database connection failed']));
        }
    }
    return $pdo;
}

// ============================================
// SECURITY HELPERS
// ============================================

function generateCSRF() {
    if (!isset($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf_token'];
}

function validateCSRF($token) {
    return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token);
}

function sanitize($input) {
    return htmlspecialchars(strip_tags(trim($input)), ENT_QUOTES, 'UTF-8');
}

function sanitizeEmail($email) {
    return filter_var(trim($email), FILTER_SANITIZE_EMAIL);
}

function validateEmail($email) {
    return filter_var($email, FILTER_VALIDATE_EMAIL);
}

function hashPassword($password) {
    return password_hash($password, PASSWORD_BCRYPT, ['cost' => 12]);
}

function verifyPassword($password, $hash) {
    return password_verify($password, $hash);
}

function generateOTP() {
    return str_pad(random_int(100000, 999999), 6, '0', STR_PAD_LEFT);
}

function generateBookingID() {
    return 'NG' . date('Ymd') . strtoupper(substr(uniqid(), -6));
}

function generateInvoiceNumber() {
    return 'INV-' . date('Y') . '-' . str_pad(random_int(1, 99999), 5, '0', STR_PAD_LEFT);
}

// ============================================
// AUTH HELPERS
// ============================================

function isUserLoggedIn() {
    return isset($_SESSION['user_id']) && !empty($_SESSION['user_id']);
}

function isLawyerLoggedIn() {
    return isset($_SESSION['lawyer_id']) && !empty($_SESSION['lawyer_id']);
}

if (!function_exists('isAdminLoggedIn')) {

    function isAdminLoggedIn() {
        return isset($_SESSION['admin_id']) && !empty($_SESSION['admin_id']);
    }

}

function requireUserLogin() {
    if (!isUserLoggedIn()) {
        header('Location: ' . SITE_URL . '/login.php?redirect=' . urlencode($_SERVER['REQUEST_URI']));
        exit;
    }
}

function requireLawyerLogin() {
    if (!isLawyerLoggedIn()) {
        header('Location: ' . SITE_URL . '/lawyer/login.php');
        exit;
    }
}

function requireAdminLogin() {
    if (!isAdminLoggedIn()) {
        header('Location: ' . SITE_URL . '/admin/login.php');
        exit;
    }
}

function getCurrentUser() {
    if (!isUserLoggedIn()) return null;
    $db = getDB();
    $stmt = $db->prepare("SELECT * FROM users WHERE id = ? AND status = 1");
    $stmt->execute([$_SESSION['user_id']]);
    return $stmt->fetch();
}

function getCurrentLawyer() {
    if (!isLawyerLoggedIn()) return null;
    $db = getDB();
    $stmt = $db->prepare("SELECT * FROM lawyers WHERE id = ? AND status = 1");
    $stmt->execute([$_SESSION['lawyer_id']]);
    return $stmt->fetch();
}

// ============================================
// UTILITY FUNCTIONS
// ============================================

function redirect($url) {
    header("Location: $url");
    exit;
}

function setFlash($type, $message) {
    $_SESSION['flash'] = ['type' => $type, 'message' => $message];
}

function getFlash() {
    if (isset($_SESSION['flash'])) {
        $flash = $_SESSION['flash'];
        unset($_SESSION['flash']);
        return $flash;
    }
    return null;
}

function formatCurrency($amount) {
    return '₹' . number_format($amount, 2);
}

function formatDate($date) {
    return date('d M Y', strtotime($date));
}

function formatDateTime($datetime) {
    return date('d M Y, h:i A', strtotime($datetime));
}

function slugify($text) {
    $text = strtolower(trim($text));
    $text = preg_replace('/[^a-z0-9-]/', '-', $text);
    $text = preg_replace('/-+/', '-', $text);
    return trim($text, '-');
}

function uploadFile($file, $dir = 'general') {
    $uploadDir = UPLOAD_DIR . $dir . '/';
    if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);
    
    $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    $filename = uniqid() . '_' . time() . '.' . $ext;
    $destination = $uploadDir . $filename;
    
    if (move_uploaded_file($file['tmp_name'], $destination)) {
        return $dir . '/' . $filename;
    }
    return false;
}

function getLawyerRatingStars($rating) {
    $stars = '';
    $fullStars = floor($rating);
    $halfStar = ($rating - $fullStars) >= 0.5;
    $emptyStars = 5 - $fullStars - ($halfStar ? 1 : 0);
    for ($i = 0; $i < $fullStars; $i++) $stars .= '<i class="fas fa-star text-warning"></i>';
    if ($halfStar) $stars .= '<i class="fas fa-star-half-alt text-warning"></i>';
    for ($i = 0; $i < $emptyStars; $i++) $stars .= '<i class="far fa-star text-warning"></i>';
    return $stars;
}

function getExperienceLabel($exp) {
    $labels = ['2-4' => '2-4 Years', '5-10' => '5-10 Years', '10+' => '10+ Years'];
    return $labels[$exp] ?? $exp;
}

function getSiteSettings() {
    static $settings = null;
    if ($settings === null) {
        $db = getDB();
        $stmt = $db->query("SELECT setting_key, setting_value FROM settings");
        $rows = $stmt->fetchAll();
        $settings = [];
        foreach ($rows as $row) {
            $settings[$row['setting_key']] = $row['setting_value'];
        }
    }
    return $settings;
}

// Send Email (basic implementation - use PHPMailer in production)
function sendEmail($to, $subject, $body, $toName = '') {
    $headers = "MIME-Version: 1.0\r\n";
    $headers .= "Content-type:text/html;charset=UTF-8\r\n";
    $headers .= "From: " . SMTP_FROM_NAME . " <" . SMTP_USERNAME . ">\r\n";
    return mail($to, $subject, $body, $headers);
}

function sendOTPEmail($email, $otp, $name) {
    $subject = "Your OTP for MeeVakeel - $otp";
    $body = "
    <div style='font-family:Arial,sans-serif;max-width:600px;margin:0 auto;'>
        <div style='background:#0A2342;padding:20px;text-align:center;'>
            <h1 style='color:#D4AF37;margin:0;'>MeeVakeel</h1>
        </div>
        <div style='padding:30px;background:#f9f9f9;'>
            <h2>Hello $name,</h2>
            <p>Your One-Time Password (OTP) for verification is:</p>
            <div style='background:#0A2342;color:#D4AF37;font-size:36px;font-weight:bold;text-align:center;padding:20px;letter-spacing:10px;border-radius:8px;'>$otp</div>
            <p style='margin-top:20px;'>This OTP is valid for " . OTP_EXPIRY_MINUTES . " minutes.</p>
            <p>If you did not request this, please ignore this email.</p>
        </div>
        <div style='background:#0A2342;padding:15px;text-align:center;color:#999;font-size:12px;'>
            <p>&copy; " . date('Y') . " MeeVakeel. All rights reserved.</p>
        </div>
    </div>";
    return sendEmail($email, $subject, $body, $name);
}

// JSON response helper
function jsonResponse($success, $message = '', $data = []) {
    header('Content-Type: application/json');
    echo json_encode(['success' => $success, 'message' => $message, 'data' => $data]);
    exit;
}