<?php
declare(strict_types=1);

require_once __DIR__ . '/_layout.php';

$pdo = financial_db();

$msg = (string)($_GET['msg'] ?? '');
$err = (string)($_GET['err'] ?? '');

financial_page_start('الكشوفات المالية');

$files = [];

function financial_current_db_name(PDO $pdo): string
{
    return (string)$pdo->query('SELECT DATABASE()')->fetchColumn();
}

function financial_table_exists_local(PDO $pdo, string $table): bool
{
    $dbName = financial_current_db_name($pdo);

    $st = $pdo->prepare("
        SELECT COUNT(*)
        FROM information_schema.TABLES
        WHERE TABLE_SCHEMA = :db
          AND TABLE_NAME = :table
    ");

    $st->execute([
        ':db'    => $dbName,
        ':table' => $table,
    ]);

    return (int)$st->fetchColumn() > 0;
}

function financial_column_exists_local(PDO $pdo, string $table, string $column): bool
{
    $dbName = financial_current_db_name($pdo);

    $st = $pdo->prepare("
        SELECT COUNT(*)
        FROM information_schema.COLUMNS
        WHERE TABLE_SCHEMA = :db
          AND TABLE_NAME = :table
          AND COLUMN_NAME = :column
    ");

    $st->execute([
        ':db'     => $dbName,
        ':table'  => $table,
        ':column' => $column,
    ]);

    return (int)$st->fetchColumn() > 0;
}

try {
    if (financial_table_exists_local($pdo, 'financial_import_files')) {
        $st = $pdo->query("
            SELECT *
            FROM financial_import_files
            ORDER BY id DESC
            LIMIT 100
        ");

        $files = $st->fetchAll(PDO::FETCH_ASSOC);

        $incomeHasImportId  = financial_table_exists_local($pdo, 'financial_income') &&
                              financial_column_exists_local($pdo, 'financial_income', 'import_file_id');

        $expenseHasImportId = financial_table_exists_local($pdo, 'financial_expenses') &&
                              financial_column_exists_local($pdo, 'financial_expenses', 'import_file_id');

        foreach ($files as &$file) {
            $file['sum_net']    = 0.00;
            $file['sum_vat']    = 0.00;
            $file['sum_amount'] = 0.00;

            $importId = (int)($file['id'] ?? 0);
            $type     = (string)($file['import_type'] ?? '');

            if ($importId <= 0) {
                continue;
            }

            if ($type === 'income' && $incomeHasImportId) {
                $sum = $pdo->prepare("
                    SELECT
                        COALESCE(SUM(net_amount), 0) AS sum_net,
                        COALESCE(SUM(vat_amount), 0) AS sum_vat,
                        COALESCE(SUM(amount), 0) AS sum_amount
                    FROM financial_income
                    WHERE import_file_id = ?
                ");
                $sum->execute([$importId]);
                $result = $sum->fetch(PDO::FETCH_ASSOC) ?: [];

                $file['sum_net']    = (float)($result['sum_net'] ?? 0);
                $file['sum_vat']    = (float)($result['sum_vat'] ?? 0);
                $file['sum_amount'] = (float)($result['sum_amount'] ?? 0);
            }

            if ($type === 'expense' && $expenseHasImportId) {
                $sum = $pdo->prepare("
                    SELECT
                        COALESCE(SUM(net_amount), 0) AS sum_net,
                        COALESCE(SUM(vat_amount), 0) AS sum_vat,
                        COALESCE(SUM(amount), 0) AS sum_amount
                    FROM financial_expenses
                    WHERE import_file_id = ?
                ");
                $sum->execute([$importId]);
                $result = $sum->fetch(PDO::FETCH_ASSOC) ?: [];

                $file['sum_net']    = (float)($result['sum_net'] ?? 0);
                $file['sum_vat']    = (float)($result['sum_vat'] ?? 0);
                $file['sum_amount'] = (float)($result['sum_amount'] ?? 0);
            }
        }
        unset($file);
    }
} catch (Throwable $e) {
    $files = [];
}
?>

<style>
.fin-import-grid{
    display:grid;
    grid-template-columns:repeat(auto-fit,minmax(320px,1fr));
    gap:18px;
}

.fin-card{
    background:rgba(255,255,255,.04);
    border:1px solid rgba(255,255,255,.08);
    border-radius:22px;
    padding:20px;
    backdrop-filter:blur(10px);
    position:relative;
    overflow:hidden;
}

.fin-card::before{
    content:"";
    position:absolute;
    inset:0;
    background:linear-gradient(120deg,transparent 20%,rgba(255,255,255,.08) 50%,transparent 80%);
    transform:translateX(-100%);
    animation:shine 6s linear infinite;
    pointer-events:none;
}

@keyframes shine{
    100%{transform:translateX(100%);}
}

.fin-title{
    font-size:20px;
    font-weight:900;
    margin-bottom:18px;
    color:#f8d56b;
}

.fin-upload-box{
    width:100%;
    min-height:54px;
    display:flex;
    align-items:center;
    padding:10px;
    border-radius:16px;
    border:1px dashed rgba(212,175,55,.45);
    background:rgba(255,255,255,.04);
}

.fin-upload-box input[type=file]{
    width:100%;
    cursor:pointer;
}

.fin-upload-box input[type=file]::file-selector-button{
    border:0;
    padding:10px 16px;
    border-radius:12px;
    font-weight:900;
    cursor:pointer;
    margin-inline-end:10px;
    background:linear-gradient(135deg,#f8d56b,#d4af37);
    color:#102326;
}

.fin-hint{
    display:block;
    margin-top:10px;
    color:rgba(255,255,255,.65);
    font-size:12px;
    line-height:1.8;
}

.fin-actions{
    margin-top:18px;
}

.fin-table-wrap{
    width:100%;
    overflow-x:auto;
    padding-bottom:10px;
}

.fin-table{
    width:100%;
    min-width:1250px;
    table-layout:auto;
    border-collapse:collapse;
}

.fin-table th,
.fin-table td{
    padding:14px 10px;
    text-align:center;
    vertical-align:middle;
    border-bottom:1px solid rgba(255,255,255,.06);
    white-space:nowrap;
}

.fin-table th{
    color:#f8d56b;
    font-weight:900;
    background:rgba(255,255,255,.04);
}

.fin-badge{
    padding:6px 12px;
    border-radius:999px;
    font-size:12px;
    font-weight:800;
    display:inline-flex;
    align-items:center;
    justify-content:center;
}

.fin-success{
    background:rgba(34,197,94,.15);
    color:#4ade80;
}

.fin-failed{
    background:rgba(239,68,68,.15);
    color:#f87171;
}

.fin-pending{
    background:rgba(245,158,11,.15);
    color:#fbbf24;
}

.fin-net{
    color:#7dd3fc;
    font-weight:900;
}

.fin-vat{
    color:#f8d56b;
    font-weight:900;
}

.fin-total{
    color:#86efac;
    font-weight:900;
}

.fin-actions-cell{
    display:flex;
    flex-direction:row;
    gap:8px;
    align-items:center;
    justify-content:center;
    flex-wrap:nowrap;
}

.fin-actions-cell form{
    margin:0;
}

.fin-actions-cell .btn,
.fin-actions-cell button.btn{
    min-width:62px;
    height:36px;
    padding:0 12px;
    border-radius:10px;
    font-size:12px;
    display:inline-flex;
    align-items:center;
    justify-content:center;
}

.fin-delete-btn{
    border-color:#ef4444 !important;
    color:#ffb4b4 !important;
}

@media (max-width:768px){
    .fin-import-grid{
        grid-template-columns:1fr;
    }

    .fin-table{
        min-width:1250px;
    }
}
</style>

<?php if ($msg !== ''): ?>
    <div class="msg ok"><?= financial_h($msg) ?></div>
<?php endif; ?>

<?php if ($err !== ''): ?>
    <div class="msg err"><?= financial_h($err) ?></div>
<?php endif; ?>

<div class="fin-import-grid">

    <div class="fin-card">
        <div class="fin-title">استيراد المدخولات</div>

        <form action="<?= financial_h(financial_u('import_process.php')) ?>"
              method="post"
              enctype="multipart/form-data">

            <input type="hidden" name="import_type" value="income">

            <div class="fin-upload-box">
                <input type="file" name="csv_file" accept=".csv,.xlsx,.xls" required>
            </div>

            <small class="fin-hint">
                ترتيب الأعمدة: التاريخ، اسم العميل، نوع الخدمة، المبلغ، طريقة الدفع، الملاحظات
            </small>

            <div class="fin-actions">
                <button class="btn primary" type="submit">استيراد المدخولات</button>
            </div>
        </form>
    </div>

    <div class="fin-card">
        <div class="fin-title">استيراد المصروفات</div>

        <form action="<?= financial_h(financial_u('import_process.php')) ?>"
              method="post"
              enctype="multipart/form-data">

            <input type="hidden" name="import_type" value="expense">

            <div class="fin-upload-box">
                <input type="file" name="csv_file" accept=".csv,.xlsx,.xls" required>
            </div>

            <small class="fin-hint">
                ترتيب الأعمدة: التاريخ، اسم المصروف، التصنيف، المبلغ، طريقة الدفع، الملاحظات
            </small>

            <div class="fin-actions">
                <button class="btn primary" type="submit">استيراد المصروفات</button>
            </div>
        </form>
    </div>

</div>

<div class="panel" style="margin-top:24px;">
    <div class="panel-head">سجل الكشوفات المالية</div>

    <div class="panel-body">
        <div class="fin-table-wrap">
            <table class="fin-table">
                <thead>
                    <tr>
                        <th>#</th>
                        <th>النوع</th>
                        <th>اسم الملف</th>
                        <th>الحالة</th>
                        <th>قبل الضريبة</th>
                        <th>VAT</th>
                        <th>شامل الضريبة</th>
                        <th>تم الاستيراد</th>
                        <th>تم التجاهل</th>
                        <th>الحجم</th>
                        <th>التاريخ</th>
                        <th>الإجراءات</th>
                    </tr>
                </thead>

                <tbody>
                <?php if (!$files): ?>
                    <tr>
                        <td colspan="12">لا توجد كشوفات مالية حتى الآن</td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($files as $row): ?>
                        <?php
                        $status = (string)($row['status'] ?? '');
                        $badgeClass = 'fin-pending';

                        if ($status === 'completed') {
                            $badgeClass = 'fin-success';
                        } elseif ($status === 'failed') {
                            $badgeClass = 'fin-failed';
                        }

                        $filePath = (string)($row['file_path'] ?? '');
                        ?>

                        <tr>
                            <td><?= (int)($row['id'] ?? 0) ?></td>

                            <td>
                                <?= financial_h(
                                    ($row['import_type'] ?? '') === 'expense'
                                        ? 'مصروفات'
                                        : 'مدخولات'
                                ) ?>
                            </td>

                            <td><?= financial_h((string)($row['original_name'] ?? '—')) ?></td>

                            <td>
                                <span class="fin-badge <?= financial_h($badgeClass) ?>">
                                    <?= financial_h($status !== '' ? $status : 'pending') ?>
                                </span>
                            </td>

                            <td class="fin-net">
                                <?= financial_h(number_format((float)($row['sum_net'] ?? 0), 2)) ?> د.إ
                            </td>

                            <td class="fin-vat">
                                <?= financial_h(number_format((float)($row['sum_vat'] ?? 0), 2)) ?> د.إ
                            </td>

                            <td class="fin-total">
                                <?= financial_h(number_format((float)($row['sum_amount'] ?? 0), 2)) ?> د.إ
                            </td>

                            <td><?= (int)($row['imported_rows'] ?? 0) ?></td>

                            <td><?= (int)($row['skipped_rows'] ?? 0) ?></td>

                            <td><?= number_format(((int)($row['file_size'] ?? 0)) / 1024, 2) ?> KB</td>

                            <td><?= financial_h((string)($row['created_at'] ?? '—')) ?></td>

                            <td>
                                <div class="fin-actions-cell">
                                    <?php if ($filePath !== ''): ?>
                                        <a class="btn soft"
                                           href="<?= financial_h($filePath) ?>"
                                           target="_blank">
                                            عرض
                                        </a>
                                    <?php else: ?>
                                        <span class="btn soft" style="opacity:.45;pointer-events:none;">عرض</span>
                                    <?php endif; ?>

                                    <form action="<?= financial_h(financial_u('import_delete.php')) ?>"
                                          method="post"
                                          onsubmit="return confirm('هل أنت متأكد من حذف هذا الكشف؟');">

                                        <input type="hidden" name="id" value="<?= (int)($row['id'] ?? 0) ?>">

                                        <button class="btn fin-delete-btn" type="submit">حذف</button>
                                    </form>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
                </tbody>

            </table>
        </div>
    </div>
</div>

<?php financial_page_end(); ?>