<?php
require_once __DIR__ . '/../config/config.php';
requireLogin();

$type = $_GET['type'] ?? 'salary'; // salary, report, site
$start_date = $_GET['start_date'] ?? date('Y-m-01');
$end_date = $_GET['end_date'] ?? date('Y-m-d');
$target_id = $_GET['target_id'] ?? ''; // employee_id or site_id
$target_type = $_GET['target_type'] ?? 'employee'; // employee, subcontractor

// 獲取預設公司資訊（用於報表抬頭）
$stmt_comp = $pdo->query("SELECT * FROM quote_companies LIMIT 1");
$company = $stmt_comp->fetch();

// 導出 Excel (CSV) 處理
if (isset($_GET['export']) && $_GET['export'] === 'excel') {
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=finance_report_' . date('Ymd') . '.csv');
    $output = fopen('php://output', 'w');
    fprintf($output, chr(0xEF).chr(0xBB).chr(0xBF)); // UTF-8 BOM

    if ($type === 'salary') {
        fputcsv($output, ['日期', '對象類型', '名稱', '地盤', '工種', '日薪/月薪', '金額']);
        // 獲取數據並寫入 CSV... (這裡簡化，實際代碼在下面獲取數據後處理)
    } elseif ($type === 'report') {
        fputcsv($output, ['類別', '項目/對象', '日期', '金額']);
    } elseif ($type === 'site') {
        fputcsv($output, ['類別', '詳情', '日期', '金額']);
    }
    
    // 這裡需要根據不同的 type 重新獲取數據並寫入 CSV
    // 為了代碼整潔，我會在下面獲取數據後，如果 export 為 true 則直接輸出並 exit
}

// 數據獲取邏輯
$data = [];
$summary = ['total_income' => 0, 'total_expense' => 0, 'total_salary' => 0];

if ($type === 'salary') {
    $table = ($target_type === 'subcontractor') ? 'subcontractors' : 'employees';
    $sql = "SELECT w.*, s.location, s.unit, t.name, t.salary_amount, t.salary_type 
            FROM work_entries w
            JOIN sites s ON w.site_id = s.id
            JOIN $table t ON w.worker_id = t.id
            WHERE w.worker_type = ? AND w.work_date BETWEEN ? AND ?";
    
    $params = [$target_type, $start_date, $end_date];
    if ($target_id) {
        $sql .= " AND w.worker_id = ?";
        $params[] = $target_id;
    }
    $sql .= " ORDER BY w.work_date DESC";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $data = $stmt->fetchAll();
} elseif ($type === 'report') {
    // 財務報表：收入 (發票) + 支出 (報銷 + 薪金)
    // 收入
    $invoices = $pdo->prepare("SELECT i.*, q.project_name FROM invoices i JOIN quotations q ON i.quotation_id = q.id WHERE i.created_at BETWEEN ? AND ?");
    $invoices->execute([$start_date . ' 00:00:00', $end_date . ' 23:59:59']);
    $data['invoices'] = $invoices->fetchAll();
    
    // 報銷
    $bills = $pdo->prepare("SELECT b.*, s.location FROM bills b JOIN sites s ON b.site_id = s.id WHERE b.bill_date BETWEEN ? AND ?");
    $bills->execute([$start_date, $end_date]);
    $data['bills'] = $bills->fetchAll();
    
    // 薪金支出
    $work_entries = $pdo->prepare("
        (SELECT w.*, e.name, e.salary_amount, 'employee' as t_type FROM work_entries w JOIN employees e ON w.worker_id = e.id WHERE w.worker_type = 'employee' AND w.work_date BETWEEN ? AND ?)
        UNION ALL
        (SELECT w.*, sc.name, sc.salary_amount, 'subcontractor' as t_type FROM work_entries w JOIN subcontractors sc ON w.worker_id = sc.id WHERE w.worker_type = 'subcontractor' AND w.work_date BETWEEN ? AND ?)
    ");
    $work_entries->execute([$start_date, $end_date, $start_date, $end_date]);
    $data['salaries'] = $work_entries->fetchAll();
} elseif ($type === 'site') {
    if ($target_id) {
        // 地盤盈虧
        // 收入
        $invoices = $pdo->prepare("SELECT i.*, q.project_name FROM invoices i JOIN quotations q ON i.quotation_id = q.id WHERE q.project_name LIKE (SELECT CONCAT('%', location, '%') FROM sites WHERE id = ?)");
        // 這裡 project_name 和 site location 的關聯可能不嚴謹，但在沒有明確 site_id 關聯 quotations 的情況下，我們假設 project_name 包含 location
        // 或者我們可以修改 quotations 表增加 site_id (更專業的做法)
        // 為了簡單起見，我們先按 project_name 模糊匹配，或者獲取地盤名稱
        $stmt_site = $pdo->prepare("SELECT location FROM sites WHERE id = ?");
        $stmt_site->execute([$target_id]);
        $site_name = $stmt_site->fetchColumn();
        
        $invoices = $pdo->prepare("SELECT i.*, q.project_name FROM invoices i JOIN quotations q ON i.quotation_id = q.id WHERE q.project_name LIKE ?");
        $invoices->execute(['%' . $site_name . '%']);
        $data['invoices'] = $invoices->fetchAll();
        
        // 支出 (報銷)
        $bills = $pdo->prepare("SELECT * FROM bills WHERE site_id = ? AND bill_date BETWEEN ? AND ?");
        $bills->execute([$target_id, $start_date, $end_date]);
        $data['bills'] = $bills->fetchAll();
        
        // 支出 (薪金)
        $work_entries = $pdo->prepare("
            (SELECT w.*, e.name, e.salary_amount FROM work_entries w JOIN employees e ON w.worker_id = e.id WHERE w.site_id = ? AND w.worker_type = 'employee' AND w.work_date BETWEEN ? AND ?)
            UNION ALL
            (SELECT w.*, sc.name, sc.salary_amount FROM work_entries w JOIN subcontractors sc ON w.worker_id = sc.id WHERE w.site_id = ? AND w.worker_type = 'subcontractor' AND w.work_date BETWEEN ? AND ?)
        ");
        $work_entries->execute([$target_id, $start_date, $end_date, $target_id, $start_date, $end_date]);
        $data['salaries'] = $work_entries->fetchAll();
    }
}

// 處理 Excel 導出數據寫入
if (isset($_GET['export']) && $_GET['export'] === 'excel') {
    if ($type === 'salary') {
        foreach ($data as $row) {
            fputcsv($output, [
                $row['work_date'], 
                $row['worker_type'] == 'employee' ? '員工' : '判工',
                $row['name'],
                $row['location'] . ($row['unit'] ? ' ' . $row['unit'] : ''),
                $row['work_type'],
                $row['salary_type'] == 'daily' ? '日薪' : '月薪',
                $row['salary_amount']
            ]);
        }
    } elseif ($type === 'report' || $type === 'site') {
        foreach ($data['invoices'] ?? [] as $inv) fputcsv($output, ['收入', '發票: ' . $inv['project_name'], date('Y-m-d', strtotime($inv['created_at'])), $inv['amount']]);
        foreach ($data['bills'] ?? [] as $bill) fputcsv($output, ['支出', '報銷: ' . $bill['description'], $bill['bill_date'], -$bill['amount']]);
        foreach ($data['salaries'] ?? [] as $sal) fputcsv($output, ['支出', '薪金: ' . $sal['name'], $sal['work_date'], -$sal['salary_amount']]);
    }
    fclose($output);
    exit;
}

// 獲取選擇清單
$employees = $pdo->query("SELECT id, name FROM employees ORDER BY name")->fetchAll();
$subcontractors = $pdo->query("SELECT id, name FROM subcontractors ORDER BY name")->fetchAll();
$sites = $pdo->query("SELECT id, location, unit FROM sites ORDER BY location")->fetchAll();

include __DIR__ . '/../includes/header.php';
?>

<div class="flex justify-between items-center mb-8 no-print">
    <div>
        <h1 class="text-2xl font-bold text-slate-800">財報計算</h1>
        <p class="text-slate-500">薪金結算、財務報表及地盤盈虧分析</p>
    </div>
    <div class="flex gap-2">
        <button onclick="window.print()" class="bg-slate-100 hover:bg-slate-200 text-slate-700 px-4 py-2 rounded-lg flex items-center transition">
            <i class="fas fa-print mr-2"></i> 列印
        </button>
        <a href="?<?php echo http_build_query(array_merge($_GET, ['export' => 'excel'])); ?>" class="bg-emerald-600 hover:bg-emerald-700 text-white px-4 py-2 rounded-lg flex items-center transition">
            <i class="fas fa-file-excel mr-2"></i> 導出 Excel
        </a>
    </div>
</div>

<!-- Tabs -->
<div class="flex border-b border-slate-200 mb-6 no-print">
    <a href="?type=salary" class="px-6 py-3 font-medium <?php echo $type === 'salary' ? 'text-blue-600 border-b-2 border-blue-600' : 'text-slate-500 hover:text-slate-700'; ?>">薪金計算</a>
    <a href="?type=report" class="px-6 py-3 font-medium <?php echo $type === 'report' ? 'text-blue-600 border-b-2 border-blue-600' : 'text-slate-500 hover:text-slate-700'; ?>">財務報表</a>
    <a href="?type=site" class="px-6 py-3 font-medium <?php echo $type === 'site' ? 'text-blue-600 border-b-2 border-blue-600' : 'text-slate-500 hover:text-slate-700'; ?>">地盤盈虧</a>
</div>

<!-- Filters -->
<div class="bg-white p-6 rounded-2xl shadow-sm border border-slate-100 mb-8 no-print">
    <form action="finance.php" method="GET" class="grid grid-cols-1 md:grid-cols-4 gap-4">
        <input type="hidden" name="type" value="<?php echo $type; ?>">
        
        <?php if ($type === 'salary'): ?>
        <div>
            <label class="block text-xs font-semibold text-slate-500 uppercase mb-1">對象類型</label>
            <select name="target_type" class="w-full px-3 py-2 border border-slate-200 rounded-lg outline-none focus:ring-2 focus:ring-blue-500">
                <option value="employee" <?php echo $target_type === 'employee' ? 'selected' : ''; ?>>員工</option>
                <option value="subcontractor" <?php echo $target_type === 'subcontractor' ? 'selected' : ''; ?>>判工</option>
            </select>
        </div>
        <div>
            <label class="block text-xs font-semibold text-slate-500 uppercase mb-1">選擇人員 (可選)</label>
            <select name="target_id" class="w-full px-3 py-2 border border-slate-200 rounded-lg outline-none focus:ring-2 focus:ring-blue-500">
                <option value="">全部人員</option>
                <?php $list = ($target_type === 'subcontractor') ? $subcontractors : $employees; ?>
                <?php foreach ($list as $item): ?>
                <option value="<?php echo $item['id']; ?>" <?php echo $target_id == $item['id'] ? 'selected' : ''; ?>><?php echo htmlspecialchars($item['name']); ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <?php elseif ($type === 'site'): ?>
        <div class="md:col-span-2">
            <label class="block text-xs font-semibold text-slate-500 uppercase mb-1">選擇地盤 *</label>
            <select name="target_id" required class="w-full px-3 py-2 border border-slate-200 rounded-lg outline-none focus:ring-2 focus:ring-blue-500">
                <option value="">-- 請選擇地盤 --</option>
                <?php foreach ($sites as $s): ?>
                <option value="<?php echo $s['id']; ?>" <?php echo $target_id == $s['id'] ? 'selected' : ''; ?>><?php echo htmlspecialchars($s['location'] . ' ' . $s['unit']); ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <?php else: ?>
        <div class="md:col-span-2"></div>
        <?php endif; ?>

        <div>
            <label class="block text-xs font-semibold text-slate-500 uppercase mb-1">開始日期</label>
            <input type="date" name="start_date" value="<?php echo $start_date; ?>" class="w-full px-3 py-2 border border-slate-200 rounded-lg outline-none focus:ring-2 focus:ring-blue-500">
        </div>
        <div>
            <label class="block text-xs font-semibold text-slate-500 uppercase mb-1">結束日期</label>
            <input type="date" name="end_date" value="<?php echo $end_date; ?>" class="w-full px-3 py-2 border border-slate-200 rounded-lg outline-none focus:ring-2 focus:ring-blue-500">
        </div>
        <div class="md:col-span-4 flex justify-end">
            <button type="submit" class="bg-blue-600 text-white px-6 py-2 rounded-lg font-bold shadow-md hover:bg-blue-700 transition">
                <i class="fas fa-search mr-2"></i> 查詢
            </button>
        </div>
    </form>
</div>

<!-- Results Area -->
<div class="bg-white rounded-2xl shadow-sm border border-slate-100 overflow-hidden print:shadow-none print:border-none print:m-0">
    <!-- Print Header -->
    <div class="hidden print:block p-8 border-b-2 border-slate-800 mb-6">
        <div class="flex justify-between items-start">
            <div>
                <h1 class="text-3xl font-bold text-slate-900 mb-2"><?php echo $company['name'] ?? APP_NAME; ?></h1>
                <div class="text-sm text-slate-600 space-y-1">
                    <?php if ($company['address']): ?><p><i class="fas fa-map-marker-alt mr-2"></i><?php echo $company['address']; ?></p><?php endif; ?>
                    <?php if ($company['phone']): ?><p><i class="fas fa-phone mr-2"></i><?php echo $company['phone']; ?></p><?php endif; ?>
                </div>
            </div>
            <div class="text-right">
                <h2 class="text-2xl font-bold text-blue-800 uppercase tracking-widest">
                    <?php 
                        if ($type === 'salary') echo '薪金清單 / SALARY REPORT';
                        elseif ($type === 'report') echo '財務明細報表 / FINANCIAL STATEMENT';
                        elseif ($type === 'site') echo '地盤盈虧分析 / PROJECT P&L ANALYSIS';
                    ?>
                </h2>
                <p class="text-slate-500 mt-2">報表日期: <?php echo $start_date; ?> 至 <?php echo $end_date; ?></p>
            </div>
        </div>
    </div>

    <div class="p-6 border-b border-slate-100 flex justify-between items-center print:hidden">
        <h2 class="text-lg font-bold text-slate-800">
            <?php 
                if ($type === 'salary') echo '薪金清單';
                elseif ($type === 'report') echo '財務明細報表';
                elseif ($type === 'site') echo '地盤盈虧分析';
            ?>
        </h2>
        <span class="text-sm text-slate-400"><?php echo $start_date; ?> 至 <?php echo $end_date; ?></span>
    </div>

    <?php if ($type === 'salary'): ?>
    <div class="overflow-x-auto">
        <table class="w-full text-left border-collapse">
            <thead class="bg-slate-50 text-slate-500 text-sm font-semibold print:bg-slate-100 print:text-slate-900">
                <tr>
                    <th class="px-6 py-4 border-b border-slate-100">日期</th>
                    <th class="px-6 py-4 border-b border-slate-100">姓名</th>
                    <th class="px-6 py-4 border-b border-slate-100">地盤</th>
                    <th class="px-6 py-4 border-b border-slate-100">工種</th>
                    <th class="px-6 py-4 border-b border-slate-100 text-right">薪金</th>
                </tr>
            </thead>
            <tbody class="divide-y divide-slate-100">
                <?php 
                $total = 0;
                foreach ($data as $row): 
                    $total += $row['salary_amount'];
                ?>
                <tr class="hover:bg-slate-50 transition print:hover:bg-transparent">
                    <td class="px-6 py-4 text-slate-500 print:text-slate-900"><?php echo $row['work_date']; ?></td>
                    <td class="px-6 py-4 font-medium text-slate-800"><?php echo htmlspecialchars($row['name']); ?></td>
                    <td class="px-6 py-4 text-slate-500 text-sm print:text-slate-900"><?php echo htmlspecialchars($row['location'] . ' ' . $row['unit']); ?></td>
                    <td class="px-6 py-4">
                        <span class="px-2 py-1 bg-slate-100 text-slate-600 rounded text-xs print:bg-transparent print:border print:border-slate-300">
                            <?php echo htmlspecialchars($row['work_type']); ?>
                        </span>
                    </td>
                    <td class="px-6 py-4 text-right font-bold text-slate-900">$<?php echo format_amount($row['salary_amount']); ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
            <tfoot>
                <tr class="bg-blue-50 font-bold print:bg-slate-50">
                    <td colspan="4" class="px-6 py-4 text-right text-blue-800 print:text-slate-900">總計 (Total)：</td>
                    <td class="px-6 py-4 text-right text-blue-800 text-xl print:text-slate-900">$<?php echo format_amount($total); ?></td>
                </tr>
            </tfoot>
        </table>
    </div>
    <?php elseif ($type === 'report' || $type === 'site'): ?>
    <div class="p-6 grid grid-cols-1 md:grid-cols-3 gap-6 mb-6 print:gap-4">
        <?php
            $income = array_sum(array_column($data['invoices'] ?? [], 'amount'));
            $bill_expense = array_sum(array_column($data['bills'] ?? [], 'amount'));
            $salary_expense = array_sum(array_column($data['salaries'] ?? [], 'salary_amount'));
            $total_expense = $bill_expense + $salary_expense;
            $profit = $income - $total_expense;
        ?>
        <div class="bg-emerald-50 p-6 rounded-xl border border-emerald-100 print:bg-transparent print:border-slate-300">
            <p class="text-emerald-600 text-xs font-bold uppercase mb-2 print:text-slate-600">總收入 (發票) / Total Income</p>
            <p class="text-3xl font-bold text-emerald-800 print:text-emerald-700">$<?php echo format_amount($income); ?></p>
        </div>
        <div class="bg-rose-50 p-6 rounded-xl border border-rose-100 print:bg-transparent print:border-slate-300">
            <p class="text-rose-600 text-xs font-bold uppercase mb-2 print:text-slate-600">總支出 (報銷+薪金) / Total Expense</p>
            <p class="text-3xl font-bold text-rose-800 print:text-rose-700">$<?php echo format_amount($total_expense); ?></p>
        </div>
        <div class="<?php echo $profit >= 0 ? 'bg-blue-50 border-blue-100' : 'bg-amber-50 border-amber-100'; ?> p-6 rounded-xl border print:bg-transparent print:border-slate-300">
            <p class="<?php echo $profit >= 0 ? 'text-blue-600' : 'text-amber-600'; ?> text-xs font-bold uppercase mb-2 print:text-slate-600">淨盈虧 / Net Profit</p>
            <p class="text-3xl font-bold <?php echo $profit >= 0 ? 'text-blue-800' : 'text-amber-800'; ?> print:text-slate-900">$<?php echo format_amount($profit); ?></p>
        </div>
    </div>

    <div class="px-6 pb-8">
        <h3 class="text-sm font-bold text-slate-400 uppercase mb-4 tracking-wider print:text-slate-900">收支明細 / Transaction Details</h3>
        <div class="overflow-x-auto">
            <table class="w-full text-left border-collapse">
                <thead class="bg-slate-50 text-slate-500 text-xs font-semibold print:bg-slate-100 print:text-slate-900">
                    <tr>
                        <th class="px-4 py-3 border-b border-slate-100">類別</th>
                        <th class="px-4 py-3 border-b border-slate-100">詳情</th>
                        <th class="px-4 py-3 border-b border-slate-100">日期</th>
                        <th class="px-4 py-3 border-b border-slate-100 text-right">金額</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-slate-100 text-sm">
                    <?php foreach ($data['invoices'] ?? [] as $inv): ?>
                    <tr class="print:hover:bg-transparent">
                        <td class="px-4 py-4"><span class="text-emerald-600 font-bold">收入</span></td>
                        <td class="px-4 py-4 text-slate-800 font-medium">工程發票: <?php echo htmlspecialchars($inv['project_name']); ?></td>
                        <td class="px-4 py-4 text-slate-400 print:text-slate-900"><?php echo date('Y-m-d', strtotime($inv['created_at'])); ?></td>
                        <td class="px-4 py-4 text-right text-emerald-600 font-bold">+$<?php echo format_amount($inv['amount']); ?></td>
                    </tr>
                    <?php endforeach; ?>
                    <?php foreach ($data['bills'] ?? [] as $bill): ?>
                    <tr class="print:hover:bg-transparent">
                        <td class="px-4 py-4"><span class="text-rose-600 font-bold">支出</span></td>
                        <td class="px-4 py-4 text-slate-800 font-medium">報銷: <?php echo htmlspecialchars($bill['description']); ?></td>
                        <td class="px-4 py-4 text-slate-400 print:text-slate-900"><?php echo $bill['bill_date']; ?></td>
                        <td class="px-4 py-4 text-right text-rose-600 font-bold">-$<?php echo format_amount($bill['amount']); ?></td>
                    </tr>
                    <?php endforeach; ?>
                    <?php foreach ($data['salaries'] ?? [] as $sal): ?>
                    <tr class="print:hover:bg-transparent">
                        <td class="px-4 py-4"><span class="text-rose-600 font-bold">支出</span></td>
                        <td class="px-4 py-4 text-slate-800 font-medium">薪金: <?php echo htmlspecialchars($sal['name']); ?> (<?php echo htmlspecialchars($sal['work_type']); ?>)</td>
                        <td class="px-4 py-4 text-slate-400 print:text-slate-900"><?php echo $sal['work_date']; ?></td>
                        <td class="px-4 py-4 text-right text-rose-600 font-bold">-$<?php echo format_amount($sal['salary_amount']); ?></td>
                    </tr>
                    <?php endforeach; ?>
                    <?php if (empty($data['invoices']) && empty($data['bills']) && empty($data['salaries'])): ?>
                    <tr>
                        <td colspan="4" class="px-4 py-16 text-center text-slate-400 italic">暫無相關收支記錄</td>
                    </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
    <?php endif; ?>

    <!-- Print Footer -->
    <div class="hidden print:flex justify-between items-center p-8 mt-12 border-t border-slate-200">
        <div class="text-xs text-slate-400">
            此報表由 <?php echo APP_NAME; ?> 自動生成 | 列印日期: <?php echo date('Y-m-d H:i'); ?>
        </div>
        <div class="w-48 border-t border-slate-900 text-center pt-2">
            <p class="text-xs font-bold">核准簽署 / AUTHORIZED BY</p>
        </div>
    </div>
</div>

<style>
@media print {
    .no-print { display: none !important; }
    body { background: white !important; }
    .container { width: 100% !important; max-width: none !important; margin: 0 !important; padding: 0 !important; }
    main { margin: 0 !important; padding: 0 !important; }
    .shadow-sm, .shadow-md, .shadow-2xl { shadow: none !important; box-shadow: none !important; }
    .rounded-2xl, .rounded-xl { border-radius: 0 !important; }
}
</style>

<?php include __DIR__ . '/../includes/footer.php'; ?>
