<?php
session_start();
if (!isset($_SESSION['user'])) {
    header("Location: ../auth/login.php");
    exit;
}

// استدعاء ملف الاتصال
require_once('../config/db.php');

/**
 * دالة حماية: التأكد من وجود دالة الترجمة لمنع الخطأ Fatal Error
 * إذا كانت موجودة مسبقاً في db.php لن يتم إعادة تعريفها
 */
if (!function_exists('__')) {
    function __($key) {
        $lang = $_SESSION['lang'] ?? 'ar';
        $path = __DIR__ . "/../languages/{$lang}.php";
        if (file_exists($path)) {
            $translations = include($path);
            return $translations[$key] ?? $key;
        }
        return $key;
    }
}

// إعدادات اللغة والاتجاه
$lang = $_SESSION['lang'] ?? 'ar';
$dir = ($lang === 'ar') ? 'rtl' : 'ltr';

if (!isset($_GET['id'])) {
    echo "رقم المعاملة غير موجود.";
    exit;
}

$id = $_GET['id'];

$stmt = $conn->prepare("SELECT * FROM expenses WHERE id = ?");
$stmt->execute([$id]);
$expense = $stmt->fetch();

if (!$expense) {
    echo "لم يتم العثور على المصروف.";
    exit;
}

/**
 * دالة تحويل المبلغ إلى كلمات حسب اللغة المختارة
 */
function numberToWords($number, $lang) {
    if ($lang === 'tr') {
        return "Yalnız " . number_format($number, 2) . " Ürdün Dinarı.";
    } elseif ($lang === 'en') {
        return "Only " . number_format($number, 2) . " Jordanian Dinars.";
    }
    return "مبلغ وقدره " . number_format($number, 2) . " ديناراً أردنياً فقط لا غير.";
}

$amount_in_words = numberToWords($expense['amount'], $lang);
?>

<!DOCTYPE html>
<html lang="<?= $lang ?>" dir="<?= $dir ?>">
<head>
    <meta charset="UTF-8">
    <title><?= __('voucher_no') ?> <?= $expense['id'] ?></title>
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;700;900&display=swap" rel="stylesheet">
    <style>
        body {
            font-family: 'Cairo', sans-serif;
            padding: 20px;
            max-width: 800px;
            margin: auto;
            color: #111827;
            background-color: #fff;
            line-height: 1.6;
        }
        .container {
            border: 3px solid #000;
            padding: 30px;
        }
        .header {
            text-align: center;
            border-bottom: 3px solid #000;
            padding-bottom: 15px;
            margin-bottom: 25px;
            position: relative;
        }
        .header img {
            height: 60px;
            margin-bottom: 10px;
        }
        .header h2 {
            margin: 5px 0;
            font-size: 24px;
            font-weight: 900;
        }
        .header h3 {
            margin: 0;
            font-size: 20px;
            font-weight: 700;
            background-color: #f3f4f6;
            padding: 5px 0;
            border: 1px solid #000;
            border-top: none;
        }
        .info-top {
            display: flex;
            justify-content: space-between;
            font-size: 14px;
            margin-bottom: 20px;
            border-bottom: 1px dashed #6b7280;
            padding-bottom: 10px;
        }
        .info-top div strong {
            display: block;
            margin-top: 5px;
        }
        .receipt-id {
            position: absolute;
            top: 0;
            /* تغيير مكان رقم السند حسب الاتجاه */
            <?= ($dir === 'rtl') ? 'left: 0;' : 'right: 0;' ?>
            border: 2px solid #000;
            padding: 5px 10px;
            font-weight: bold;
            font-size: 16px;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 30px;
            font-size: 15px;
        }
        th, td {
            padding: 12px 10px;
            border: 1px solid #000;
            text-align: <?= ($dir === 'rtl') ? 'right' : 'left' ?>;
        }
        th {
            background-color: #e5e7eb;
            font-weight: 700;
            text-align: center;
        }
        .amount-row td {
            font-size: 18px;
            font-weight: 900;
            background-color: #fef2f2;
            color: #dc2626;
            text-align: center;
        }
        .notes-section {
            border: 1px solid #000;
            padding: 15px;
            margin-bottom: 40px;
        }
        .signatures {
            display: flex;
            justify-content: space-around;
            margin-top: 60px;
            font-size: 14px;
            text-align: center;
        }
        .signature-box {
            width: 180px;
            padding-top: 15px;
            border-top: 1px solid #000;
        }
        
        @media print {
            body { padding: 0; }
            .container { border: none; padding: 0; margin: 0; box-shadow: none; }
            .header h3 {
                 background-color: transparent !important;
                 -webkit-print-color-adjust: exact;
            }
            th {
                background-color: #e5e7eb !important;
                 -webkit-print-color-adjust: exact;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <img src="../assets/logo.png" alt="Logo"> 
            
            <h2><?= __('academy_name') ?></h2>
            <p style="margin: 0; font-size: 13px;"><?= __('academy_contact') ?></p>
            
            <h3 style="margin-top: 15px;"><?= __('voucher_title') ?></h3>
            
            <div class="receipt-id"><?= __('voucher_id_label') ?>: <?= htmlspecialchars($expense['id']) ?></div>
        </div>

        <div class="info-top">
            <div>
                <span><?= __('date_label') ?>:</span> 
                <strong><?= htmlspecialchars($expense['expense_date']) ?></strong>
            </div>
            <div>
                <span><?= __('paid_to_label_print') ?>:</span> 
                <strong><?= htmlspecialchars($expense['paid_to'] ?: __('not_defined')) ?></strong>
            </div>
            <div>
                <span><?= __('branch_label_print') ?>:</span> 
                <strong><?= htmlspecialchars($expense['branch_name'] ?: __('main_branch')) ?></strong>
            </div>
        </div>

        <table>
            <thead>
                <tr>
                    <th style="width: 20%;"><?= __('exp_type_col') ?></th>
                    <th><?= __('desc_col') ?></th>
                    <th style="width: 15%;"><?= __('amount_col') ?> (<?= __('currency_short') ?>)</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td style="text-align: center;"><?= htmlspecialchars($expense['expense_type']) ?></td>
                    <td><?= htmlspecialchars($expense['description'] ?: __('no_desc')) ?></td>
                    <td style="text-align: center; font-weight: bold;"><?= number_format($expense['amount'], 2) ?></td>
                </tr>
                <tr><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td></tr>
                <tr><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td></tr>
                
                <tr class="amount-row">
                    <td colspan="2" style="text-align: <?= ($dir === 'rtl') ? 'left' : 'right' ?>; font-weight: bold; padding-<?= ($dir === 'rtl') ? 'left' : 'right' ?>: 20px;">
                        <?= __('total_label') ?>
                    </td>
                    <td style="font-weight: 900; font-size: 20px;">
                        <?= number_format($expense['amount'], 2) ?> <?= __('currency_short') ?>
                    </td>
                </tr>
            </tbody>
        </table>
        
        <div class="notes-section" style="font-size: 16px; font-weight: 700; background-color: #f7f7f7;">
            <p style="margin: 0;">&mdash; <?= __('amount_written_label') ?>: <?= $amount_in_words ?></p>
        </div>

        <p style="text-align: <?= ($dir === 'rtl') ? 'right' : 'left' ?>; margin-top: 10px; font-size: 13px;"><?= __('print_date_label') ?>: <?= date('Y-m-d H:i') ?></p>

        <div class="signatures">
            <div class="signature-box"><?= __('recipient_sig') ?></div>
            <div class="signature-box"><?= __('accountant_sig') ?></div>
            <div class="signature-box"><?= __('manager_sig') ?></div>
        </div>
    </div>
    
    <script>
        window.onload = () => {
            window.print();
            window.onafterprint = () => window.close();
        };
    </script>
</body>
</html>