<?php
// admin_panel.php
header('Content-Type: text/html; charset=utf-8');
require 'db.php';
require 'auth.php';
require 'system_log_helper.php';

require_login();
$user = current_user();

// Sadece admin
if ($user['role'] != 1) {
    die("Bu sayfaya erişim yetkiniz yok.");
}

system_log('page_view', 'admin_panel.php?'.($_SERVER['QUERY_STRING'] ?? ''));

// ---------- ÖZET KARTLAR ----------

// Toplam aktif iş (tamamlandı + iptal hariç)
$stmt = $pdo->query("
    SELECT COUNT(*) AS cnt 
    FROM jobs 
    WHERE status NOT IN ('tamamlandı', 'iptal')
");
$total_active = (int)$stmt->fetchColumn();

// Bugünkü yeni iş (created_at varsa)
$stmt = $pdo->query("
    SELECT COUNT(*) AS cnt 
    FROM jobs 
    WHERE DATE(created_at) = CURDATE()
");
$today_new = (int)$stmt->fetchColumn();

// Parça bekleyen iş sayısı
$stmt = $pdo->query("
    SELECT COUNT(*) AS cnt 
    FROM jobs 
    WHERE status = 'parça_bekleniyor'
");
$waiting_parts = (int)$stmt->fetchColumn();

// En çok iş alan teknisyenler (genel)
$stmt = $pdo->query("
    SELECT 
        u.name AS tech_name,
        COUNT(j.id) AS job_count
    FROM jobs j
    LEFT JOIN users u ON j.technician_id = u.id
    WHERE j.technician_id IS NOT NULL
    GROUP BY j.technician_id
    ORDER BY job_count DESC
    LIMIT 5
");
$top_techs = $stmt->fetchAll(PDO::FETCH_ASSOC);
// ----- MOD (gün / hafta / ay) -----
$mode = $_GET['mode'] ?? 'day';
$allowedModes = ['day', 'week', 'month'];
if (!in_array($mode, $allowedModes, true)) {
    $mode = 'day';
}

// Tarih filtresi (referans tarih, default: bugün)
$date = $_GET['date'] ?? date('Y-m-d');
$date = trim($date);

// Güvenlik: format kontrolü
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) {
    $date = date('Y-m-d');
}

$ts = strtotime($date);

// ----- TARİH ARALIĞINI HESAPLA -----
if ($mode === 'day') {
    $startDate = $date;
    $endDate   = $date;
    $rangeLabel = $date . ' (Günlük)';
} elseif ($mode === 'week') {
    // ISO haftası: Pazartesi başlangıç
    $dow = (int)date('N', $ts); // 1 (Mon) - 7 (Sun)
    $startTs = strtotime('-' . ($dow - 1) . ' days', $ts);
    $endTs   = strtotime('+' . (7 - $dow) . ' days', $ts);

    $startDate = date('Y-m-d', $startTs);
    $endDate   = date('Y-m-d', $endTs);
    $rangeLabel = $startDate . ' - ' . $endDate . ' (Haftalık)';
} else { 
    // month
    $year  = date('Y', $ts);
    $month = date('m', $ts);
    $startDate = $year . '-' . $month . '-01';
    $endDate   = $year . '-' . $month . '-' . date('t', $ts); // ayın son günü
    $rangeLabel = $year . '-' . $month . ' (Aylık)';
}

// 1) Genel özet: toplam iş, durumlara göre sayılar, toplam fiyat & kapora
$summaryStmt = $pdo->prepare("
    SELECT
        COUNT(*) AS total_jobs,
        SUM(CASE WHEN status = 'yeni' THEN 1 ELSE 0 END)             AS cnt_yeni,
        SUM(CASE WHEN status = 'atandı' THEN 1 ELSE 0 END)           AS cnt_atandi,
        SUM(CASE WHEN status = 'yolda' THEN 1 ELSE 0 END)            AS cnt_yolda,
        SUM(CASE WHEN status = 'işlemde' THEN 1 ELSE 0 END)          AS cnt_islemde,
        SUM(CASE WHEN status = 'parça_bekleniyor' THEN 1 ELSE 0 END) AS cnt_parca,
        SUM(CASE WHEN status = 'tamamlandı' THEN 1 ELSE 0 END)       AS cnt_tamam,
        SUM(CASE WHEN status = 'iptal' THEN 1 ELSE 0 END)            AS cnt_iptal,
        SUM(price)  AS total_price,
        SUM(deposit) AS total_deposit
    FROM jobs
    WHERE DATE(created_at) BETWEEN ? AND ?
");
$summaryStmt->execute([$startDate, $endDate]);
$summary = $summaryStmt->fetch(PDO::FETCH_ASSOC);

// ---------- TEKNİSYEN LİSTESİ (rapor filtresi için) ----------
$stmt = $pdo->query("SELECT id, name FROM users WHERE role = 3 ORDER BY name");
$technicians = $stmt->fetchAll(PDO::FETCH_ASSOC);

// ---------- TEKNİSYEN BAZLI RAPOR FİLTRESİ ----------
$selected_tech_id = $_GET['tech_id'] ?? '';
$start_date       = $_GET['start_date'] ?? '';
$end_date         = $_GET['end_date'] ?? '';

// Varsayılan: son 7 gün
if ($start_date === '') {
    $start_date = date('Y-m-d', strtotime('-7 days'));
}
if ($end_date === '') {
    $end_date = date('Y-m-d');
}

// Rapor için temel koşullar
$where = [];
$params = [];

// Sadece tamamlanan işler
$where[] = "status = 'tamamlandı'";

// Tarih aralığı (created_at)
$where[]      = "DATE(created_at) BETWEEN ? AND ?";
$params[]     = $start_date;
$params[]     = $end_date;

// Teknisyen seçilmişse
if ($selected_tech_id !== '') {
    $where[]  = "technician_id = ?";
    $params[] = $selected_tech_id;
}

$whereSql = implode(" AND ", $where);

// Tamamlanan iş sayısı + toplam ciro
$sql = "
    SELECT 
        COUNT(*) AS completed_jobs,
        COALESCE(SUM(price), 0) AS total_revenue
    FROM jobs
    WHERE $whereSql
";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$tech_report = $stmt->fetch(PDO::FETCH_ASSOC);

$completed_jobs = (int)($tech_report['completed_jobs'] ?? 0);
$total_revenue  = (float)($tech_report['total_revenue'] ?? 0.0);

// İsteğe bağlı: Son 10 tamamlanan iş
$sql = "
    SELECT 
        j.id,
        j.title,
        j.customer_name,
        j.price,
        j.created_at,
        u.name AS tech_name
    FROM jobs j
    LEFT JOIN users u ON j.technician_id = u.id
    WHERE $whereSql
    ORDER BY j.created_at DESC
    LIMIT 10
";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$last_completed_jobs = $stmt->fetchAll(PDO::FETCH_ASSOC);

// ---------- TEKRAR EDEN İŞ RAPORU ----------

// Marka / cihaz bazlı
$stmt = $pdo->query("
    SELECT 
        title,
        COUNT(*) AS cnt
    FROM jobs
    WHERE repeat_job = 1
    GROUP BY title
    HAVING title IS NOT NULL AND title <> ''
    ORDER BY cnt DESC
    LIMIT 10
");
$repeat_by_title = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Müşteri bazlı
$stmt = $pdo->query("
    SELECT 
        customer_name,
        customer_phone,
        COUNT(*) AS cnt
    FROM jobs
    WHERE repeat_job = 1
    GROUP BY customer_name, customer_phone
    HAVING customer_name IS NOT NULL AND customer_name <> ''
    ORDER BY cnt DESC
    LIMIT 10
");
$repeat_by_customer = $stmt->fetchAll(PDO::FETCH_ASSOC);

?>
<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <title>Admin Paneli - Özet ve Raporlar</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="style.css">

    <style>
        .dashboard-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
            gap: 10px;
            margin-bottom: 20px;
        }
        .dash-card {
            padding: 12px;
            border-radius: 6px;
            background: #f5f5f5;
        }
        .dash-card h3 {
            margin: 0 0 5px;
            font-size: 14px;
            color: #555;
        }
        .dash-card .number {
            font-size: 22px;
            font-weight: bold;
            color: #222;
        }
        .table-wrapper {
            overflow-x: auto;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            font-size: 13px;
        }
        th, td {
            border: 1px solid #ddd;
            padding: 6px 8px;
            text-align: left;
        }
        th {
            background: #f0f0f0;
        }
        .section-title {
            margin-top: 25px;
            margin-bottom: 10px;
            font-size: 18px;
        }
        form.inline-form {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            align-items: center;
            margin-bottom: 10px;
        }
        form.inline-form label {
            font-size: 13px;
        }
        form.inline-form select,
        form.inline-form input[type="date"] {
            padding: 4px 6px;
            font-size: 13px;
        }
        @media (max-width: 600px) {
            .section-title {
                font-size: 16px;
            }
        }
    </style>
</head>
<body>
<div class="container">

    <div class="top-bar">
        <div><strong>Hoş geldin, <?php echo htmlspecialchars($user['name']); ?></strong></div>
        <div>
            <a href="jobs.php" class="btn">İşler</a>
            <a href="technician_create.php" class="btn">Teknisyen Ekle</a>
            <a href="user_callcenter_add.php" class="btn">Çağrı Merkezi Ekle</a>
            <a href="admin_panel.php" class="btn">Admin Paneli</a>
            <a href="logout.php" class="btn">Çıkış</a>
        </div>
    </div>
    <div class="card">
        <h1>Rapor</h1>

        <!-- Tarih & Mod seçimi -->
        <form method="get" style="margin-bottom:15px; display:flex; gap:10px; flex-wrap:wrap; align-items:center;">
            <label>
                Tarih:
                <input type="date" name="date" value="<?php echo htmlspecialchars($date); ?>"
                       onchange="this.form.submit()">
            </label>

            <label>
                Görünüm:
                <select name="mode" onchange="this.form.submit()">
                    <option value="day"   <?php echo $mode === 'day'   ? 'selected' : ''; ?>>Günlük</option>
                    <option value="week"  <?php echo $mode === 'week'  ? 'selected' : ''; ?>>Haftalık</option>
                    <option value="month" <?php echo $mode === 'month' ? 'selected' : ''; ?>>Aylık</option>
                </select>
            </label>

            <!-- Hızlı kısayollar -->
            <a href="admin_panel.php?mode=day&date=<?php echo date('Y-m-d'); ?>" class="btn">Bugün</a>
            <a href="admin_panel.php?mode=week&date=<?php echo date('Y-m-d'); ?>" class="btn">Bu Hafta</a>
            <a href="admin_panel.php?mode=month&date=<?php echo date('Y-m-d'); ?>" class="btn">Bu Ay</a>
        </form>

        <!-- Genel Özet -->
        <h2>Genel Özet (<?php echo htmlspecialchars($rangeLabel); ?>)</h2>

        <?php if ($summary && $summary['total_jobs'] > 0): ?>
            <div style="display:flex; flex-wrap:wrap; gap:15px;">

                <div class="card" style="flex:1; min-width:220px;">
                    <h3>Toplam İş</h3>
                    <p style="font-size:24px; font-weight:bold;">
                        <?php echo (int)$summary['total_jobs']; ?> adet
                    </p>
                </div>

                <div class="card" style="flex:1; min-width:220px;">
                    <h3>Durumlara Göre</h3>
                    <ul style="list-style:none; padding-left:0;">
                        <li>Yeni: <?php echo (int)$summary['cnt_yeni']; ?></li>
                        <li>Atandı: <?php echo (int)$summary['cnt_atandi']; ?></li>
                        <li>Yolda: <?php echo (int)$summary['cnt_yolda']; ?></li>
                        <li>İşlemde: <?php echo (int)$summary['cnt_islemde']; ?></li>
                        <li>Parça Bekleniyor: <?php echo (int)$summary['cnt_parca']; ?></li>
                        <li>Tamamlandı: <?php echo (int)$summary['cnt_tamam']; ?></li>
                        <li>İptal: <?php echo (int)$summary['cnt_iptal']; ?></li>
                    </ul>
                </div>

                <div class="card" style="flex:1; min-width:220px;">
                    <h3>Gelir Özeti</h3>
                    <p>Toplam Kapora: <strong><?php echo number_format((float)$summary['total_deposit'], 2); ?> TL</strong></p>
                    <p>Toplam Fiyat: <strong><?php echo number_format((float)$summary['total_price'], 2); ?> TL</strong></p>
                </div>

            </div>
        <?php else: ?>
            <p>Bu tarih aralığında kayıtlı iş bulunamadı.</p>
        <?php endif; ?>
    </div>
    <div class="card">
        <h1>Yönetim Özeti</h1>

        <!-- ÖZET KARTLAR -->
        <div class="dashboard-grid">
            <div class="dash-card">
                <h3>Toplam Aktif İş</h3>
                <div class="number"><?php echo $total_active; ?></div>
            </div>
            <div class="dash-card">
                <h3>Bugünkü Yeni İş</h3>
                <div class="number"><?php echo $today_new; ?></div>
            </div>
            <div class="dash-card">
                <h3>Parça Bekleyen İş</h3>
                <div class="number"><?php echo $waiting_parts; ?></div>
            </div>
        </div>

        <!-- En çok iş alan teknisyenler -->
        <h2 class="section-title">En Çok İş Alan Teknisyenler</h2>
        <div class="table-wrapper">
            <table>
                <tr>
                    <th>Teknisyen</th>
                    <th>İş Sayısı</th>
                </tr>
                <?php if (empty($top_techs)): ?>
                    <tr><td colspan="2">Kayıt bulunamadı.</td></tr>
                <?php else: ?>
                    <?php foreach ($top_techs as $t): ?>
                        <tr>
                            <td><?php echo htmlspecialchars($t['tech_name'] ?? '-'); ?></td>
                            <td><?php echo (int)$t['job_count']; ?></td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </table>
        </div>

        <!-- TEKNİSYEN BAZLI RAPOR -->
        <h2 class="section-title">Teknisyen Bazlı Rapor</h2>

        <form method="get" class="inline-form">
            <label>
                Teknisyen:
                <select name="tech_id">
                    <option value="">Tümü</option>
                    <?php foreach ($technicians as $tech): ?>
                        <option value="<?php echo $tech['id']; ?>"
                            <?php echo ($selected_tech_id == $tech['id']) ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($tech['name']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </label>

            <label>
                Başlangıç:
                <input type="date" name="start_date" value="<?php echo htmlspecialchars($start_date); ?>">
            </label>

            <label>
                Bitiş:
                <input type="date" name="end_date" value="<?php echo htmlspecialchars($end_date); ?>">
            </label>

            <button type="submit" class="btn">Filtrele</button>
        </form>

        <p>
            Seçilen aralıkta <strong><?php echo $completed_jobs; ?></strong> adet
            tamamlanan iş var. <br>
            Toplam tahmini ciro: <strong><?php echo number_format($total_revenue, 2, ',', '.'); ?> TL</strong>
        </p>

        <h3>Son 10 Tamamlanan İş</h3>
        <div class="table-wrapper">
            <table>
                <tr>
                    <th>ID</th>
                    <th>Teknisyen</th>
                    <th>Marka / Cihaz</th>
                    <th>Müşteri</th>
                    <th>Fiyat (TL)</th>
                    <th>Tarih</th>
                </tr>
                <?php if (empty($last_completed_jobs)): ?>
                    <tr><td colspan="6">Kayıt bulunamadı.</td></tr>
                <?php else: ?>
                    <?php foreach ($last_completed_jobs as $row): ?>
                        <tr>
                            <td><?php echo $row['id']; ?></td>
                            <td><?php echo htmlspecialchars($row['tech_name'] ?? '-'); ?></td>
                            <td><?php echo htmlspecialchars($row['title'] ?? '-'); ?></td>
                            <td><?php echo htmlspecialchars($row['customer_name'] ?? '-'); ?></td>
                            <td><?php echo $row['price'] !== null ? number_format($row['price'], 2, ',', '.') : '-'; ?></td>
                            <td><?php echo htmlspecialchars($row['created_at'] ?? '-'); ?></td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </table>
        </div>

        <!-- TEKRAR EDEN İŞ RAPORU -->
        <h2 class="section-title">Tekrar Eden İşler (repeat_job = 1)</h2>

        <h3>En Çok Tekrarlanan Marka / Cihaz</h3>
        <div class="table-wrapper">
            <table>
                <tr>
                    <th>Marka / Cihaz</th>
                    <th>Tekrar Sayısı</th>
                </tr>
                <?php if (empty($repeat_by_title)): ?>
                    <tr><td colspan="2">Kayıt bulunamadı.</td></tr>
                <?php else: ?>
                    <?php foreach ($repeat_by_title as $r): ?>
                        <tr>
                            <td><?php echo htmlspecialchars($r['title'] ?? '-'); ?></td>
                            <td><?php echo (int)$r['cnt']; ?></td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </table>
        </div>

        <h3>En Çok Tekrarlayan Müşteriler</h3>
        <div class="table-wrapper">
            <table>
                <tr>
                    <th>Müşteri Adı</th>
                    <th>Telefon</th>
                    <th>Tekrar Sayısı</th>
                </tr>
                <?php if (empty($repeat_by_customer)): ?>
                    <tr><td colspan="3">Kayıt bulunamadı.</td></tr>
                <?php else: ?>
                    <?php foreach ($repeat_by_customer as $r): ?>
                        <tr>
                            <td><?php echo htmlspecialchars($r['customer_name'] ?? '-'); ?></td>
                            <td><?php echo htmlspecialchars($r['customer_phone'] ?? '-'); ?></td>
                            <td><?php echo (int)$r['cnt']; ?></td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </table>
        </div>

    </div>
</div>

</body>
</html>
