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

require_login();
$user = current_user();

$errors  = [];
$success = '';

/* ============================================================
   İŞ SİLME (SADECE ADMIN)
   ============================================================ */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_job'])) {

    if ($user['role'] != 1) {
        die("Bu işlemi yapmaya yetkiniz yok.");
    }

    $jobId = (int)$_POST['delete_job'];

    if ($jobId <= 0) {
        $errors[] = "Geçersiz iş ID.";
    } else {
        try {
            $pdo->beginTransaction();

            // Fotoğrafları al ve diskte sil
            $fStmt = $pdo->prepare("SELECT file_path FROM job_files WHERE job_id = ?");
            $fStmt->execute([$jobId]);
            $files = $fStmt->fetchAll(PDO::FETCH_COLUMN);

            if (!empty($files)) {
                foreach ($files as $fp) {
                    $full = __DIR__ . '/' . $fp;
                    if (is_file($full)) {
                        @unlink($full);
                    }
                }
            }

            // job_files
            $delFiles = $pdo->prepare("DELETE FROM job_files WHERE job_id = ?");
            $delFiles->execute([$jobId]);

            // job_logs
            $delLogs = $pdo->prepare("DELETE FROM job_logs WHERE job_id = ?");
            $delLogs->execute([$jobId]);

            // job kaydı
            $delJob = $pdo->prepare("DELETE FROM jobs WHERE id = ?");
            $delJob->execute([$jobId]);

            $pdo->commit();
            $success = "İş ve ilişkili kayıtlar silindi.";

        } catch (Exception $e) {
            $pdo->rollBack();
            $errors[] = "İş silinemedi: " . $e->getMessage();
        }
    }
}

// ---- DURUM FİLTRESİ ----
$statusFilter = $_GET['status'] ?? '';
$statusFilter = trim($statusFilter);

$validStatuses = ['yeni', 'atandı', 'yolda', 'işlemde', 'parça_bekleniyor', 'tamamlandı', 'iptal'];
$filterActive  = in_array($statusFilter, $validStatuses, true);

// ---- ARAMA FİLTRESİ (isim / telefon) ----
$search = $_GET['q'] ?? '';
$search = trim($search);
$searchActive = ($search !== '');

// ---- SORGULAR ----
if ($user['role'] == 1 || $user['role'] == 2) {
    // Admin & Çağrı Merkezi: tüm işler
    // j = jobs, u1 = teknisyen, u2 = ekleyen (call center / admin)
    $sql = "
        SELECT 
            j.*,
            u1.name AS tech_name,
            u2.name AS callcenter_name
        FROM jobs j
        LEFT JOIN users u1 ON j.technician_id = u1.id
        LEFT JOIN users u2 ON j.created_by     = u2.id
    ";

    $conditions = [];
    $params     = [];

    if ($filterActive) {
        $conditions[] = "j.status = ?";
        $params[]     = $statusFilter;
    }

    if ($searchActive) {
        $conditions[] = "(j.customer_name LIKE ? 
                          OR j.customer_phone LIKE ?
                          OR j.customer_phone2 LIKE ?)";
        $like = '%'.$search.'%';
        $params[] = $like;
        $params[] = $like;
        $params[] = $like;
    }

    if (!empty($conditions)) {
        $sql .= " WHERE ".implode(" AND ", $conditions);
    }

    $sql .= " ORDER BY j.id DESC";

    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);

} else {
    // Teknisyen: sadece kendine atanmış işler
    $sql = "
        SELECT 
            j.*,
            u1.name AS tech_name,
            u2.name AS callcenter_name
        FROM jobs j
        LEFT JOIN users u1 ON j.technician_id = u1.id
        LEFT JOIN users u2 ON j.created_by     = u2.id
        WHERE j.technician_id = ?
    ";

    $conditions = [];
    $params     = [$user['id']];

    if ($filterActive) {
        $conditions[] = "j.status = ?";
        $params[]     = $statusFilter;
    }

    if ($searchActive) {
        $conditions[] = "(j.customer_name LIKE ?
                          OR j.customer_phone LIKE ?
                          OR j.customer_phone2 LIKE ?)";
        $like = '%'.$search.'%';
        $params[] = $like;
        $params[] = $like;
        $params[] = $like;
    }

    if (!empty($conditions)) {
        $sql .= " AND ".implode(" AND ", $conditions);
    }

    $sql .= " ORDER BY j.id DESC";

    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
}

$jobs = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Teknisyen için "yeni / atandı" uyarısı
$has_new_job = false;
if ($user['role'] == 3) {
    foreach ($jobs as $j) {
        if (in_array($j['status'], ['yeni', 'atandı'])) {
            $has_new_job = true;
            break;
        }
    }
}

// Durum label'ları (görsel için)
$statusLabels = [
    'yeni'             => 'Yeni',
    'atandı'           => 'Atandı',
    'yolda'            => 'Yolda',
    'işlemde'          => 'İşlemde',
    'parça_bekleniyor' => 'Parça Bekleniyor',
    'tamamlandı'       => 'Tamamlandı',
    'iptal'            => 'İptal'
];

?><!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>İş Listesi</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">

    <div class="top-bar">
        <div><strong>Hoş geldin, <?php echo htmlspecialchars($user['name']); ?></strong></div>
        <div>
            <?php if ($user['role'] == 1): ?>
                <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="users.php" class="btn">Kullanıcılar</a>
                <a href="admin_panel.php" class="btn">Admin Paneli</a>
            <?php endif; ?>
            <a href="logout.php" class="btn">Çıkış</a>
        </div>
    </div>

    <?php if ($user['role'] == 3 && $has_new_job): ?>
        <div class="card alert alert-warning">
            <strong>Yeni işiniz var!</strong> Atanmış bekleyen işleriniz bulunuyor.
        </div>
    <?php endif; ?>

    <div class="card">

        <?php if ($user['role'] == 1 || $user['role'] == 2): ?>
            <p><a href="job_edit.php" class="btn">+ Yeni İş Ekle</a></p>
        <?php endif; ?>

        <?php if (!empty($errors)): ?>
            <div class="alert alert-danger">
                <ul>
                    <?php foreach ($errors as $e): ?>
                        <li><?php echo htmlspecialchars($e); ?></li>
                    <?php endforeach; ?>
                </ul>
            </div>
        <?php endif; ?>

        <?php if ($success): ?>
            <div class="alert alert-success">
                <?php echo htmlspecialchars($success); ?>
            </div>
        <?php endif; ?>

        <!-- FİLTRE + ARAMA FORMU -->
        <form method="get" style="margin-bottom:15px; display:flex; gap:10px; flex-wrap:wrap; align-items:center;">
            <label>
                Duruma göre filtrele:
                <select name="status" onchange="this.form.submit()">
                    <option value="">Tüm Durumlar</option>
                    <?php foreach ($validStatuses as $st): ?>
                        <option value="<?php echo htmlspecialchars($st); ?>"
                            <?php echo ($statusFilter === $st) ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($statusLabels[$st] ?? $st); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </label>

            <label>
                Ara (isim / telefon):
                <input type="text" name="q"
                       value="<?php echo htmlspecialchars($search); ?>"
                       placeholder="Müşteri adı veya telefon">
            </label>

            <button type="submit" class="btn">Ara</button>

            <?php if ($filterActive || $searchActive): ?>
                <a href="jobs.php" class="btn">Tümünü Göster</a>
            <?php endif; ?>
        </form>

        <div class="table-wrapper">
            <table>
                <tr>
                    <th>ID</th>
                    <th>Marka/Cihaz</th>
                    <th>Müşteri</th>
                    <th>Durum</th>
                    <th>Ekleyen</th>
                    <th>Teknisyen</th>
                    <th>İşlem</th>
                </tr>

                <?php if (empty($jobs)): ?>
                    <tr>
                        <td colspan="7" style="text-align:center;">Kayıt bulunamadı.</td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($jobs as $job): ?>
                        <tr>
                            <td><?php echo $job['id']; ?></td>
                            <td><?php echo htmlspecialchars($job['title']); ?></td>
                            <td><?php echo htmlspecialchars($job['customer_name'] ?? '-'); ?></td>
                            <td>
                                <?php
                                $st = $job['status'] ?? '';
                                echo htmlspecialchars($statusLabels[$st] ?? $st);
                                ?>
                            </td>
                            <td><?php echo htmlspecialchars($job['callcenter_name'] ?? '-'); ?></td>
                            <td><?php echo htmlspecialchars($job['tech_name'] ?? '-'); ?></td>
                            <td>
                                <?php
                                if ($user['role'] == 1 || $user['role'] == 2) {
                                    // Admin & çağrı merkezi
                                    ?>
                                    <a href="job_edit.php?id=<?php echo $job['id']; ?>" class="btn">Düzenle</a>
                                    <a href="job_service_form.php?id=<?php echo $job['id']; ?>" class="btn">Yazdır</a>
                                    <?php if ($user['role'] == 1): ?>
                                        <form method="post" style="display:inline;"
                                              onsubmit="return confirm('Bu işi ve tüm fotoğraflarını/loglarını silmek istiyor musunuz?');">
                                            <input type="hidden" name="delete_job" value="<?php echo $job['id']; ?>">
                                            <button type="submit" class="btn" style="background:#d9534f;color:#fff;">
                                                Sil
                                            </button>
                                        </form>
                                    <?php endif; ?>
                                    <?php
                                } else {
                                    // Teknisyen için düğmeler
                                    $status = $job['status'];

                                    if ($status === 'yeni') {
                                        ?>
                                        <a href="job_edit.php?id=<?php echo $job['id']; ?>" class="btn">İşe Başla</a>
                                        <?php
                                    } elseif (in_array($status, ['yolda', 'işlemde', 'parça_bekleniyor'])) {
                                        ?>
                                        <a href="job_edit.php?id=<?php echo $job['id']; ?>" class="btn">Devam Et</a>
                                        <a href="job_service_form.php?id=<?php echo $job['id']; ?>" class="btn">Yazdır</a>
                                        <?php
                                    } elseif ($status === 'tamamlandı') {
                                        ?>
                                        <a href="job_edit.php?id=<?php echo $job['id']; ?>" class="btn">Görüntüle</a>
                                        <a href="job_service_form.php?id=<?php echo $job['id']; ?>" class="btn">Yazdır</a>
                                        <?php
                                    } else {
                                        echo "-";
                                    }
                                }
                                ?>
                                
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>

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

</div>
</body>
</html>
