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

require_login();
$user = current_user();

// sayfa görüntüleme logu
system_log('page_view', 'jobs.php?'.($_SERVER['QUERY_STRING'] ?? ''));

$job_id  = $_GET['id'] ?? null;
$editing = $job_id !== null;

$job = null;
$extra_parts_existing = [];

if ($editing) {
    $stmt = $pdo->prepare("SELECT * FROM jobs WHERE id = ?");
    $stmt->execute([$job_id]);
    $job = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$job) {
        die("İş bulunamadı.");
    }

    // Teknisyen ise ve bu iş ona ait değilse: yasak
    if ($user['role'] == 3 && $job['technician_id'] != $user['id']) {
        die("Bu işi düzenleme yetkiniz yok.");
    }

    if (!empty($job['spare_parts_extra'])) {
        $extra_parts_existing = preg_split('/\r\n|\r|\n/', $job['spare_parts_extra']);
    }
}

$isTech          = ($user['role'] == 3);
$isCompletedTech = ($editing && $isTech && ($job['status'] ?? '') === 'tamamlandı');

// Sadece TEKNİSYEN + DURUM = 'yeni' ise parola istensin
$require_password = false;
if ($editing && $isTech && ($job['status'] ?? '') === 'yeni' && !empty($job['job_password'])) {
    $require_password = true;
}

// ---- İŞ PAROLASI GÜVENLİK KONTROLÜ ----
$password_error = '';
$has_access     = true;


// Parola zorunluluğu: SADECE TEKNİSYEN + DURUM = 'yeni'
if ($require_password) {

    if (!isset($_SESSION['job_access'])) {
        $_SESSION['job_access'] = [];
    }

    $has_access = !empty($_SESSION['job_access'][$job_id]);

    // Sadece parola formu gönderildiyse
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['password_check'])) {
        $input = trim($_POST['job_password_input'] ?? '');
        $real  = (string)($job['job_password'] ?? '');

        if ($input === $real && $real !== '') {
            // Teknisyen artık bu işe tam erişebilir
            $_SESSION['job_access'][$job_id] = true;

            // Parola girildikten sonra iş durumu "işlemde" olsun
            if (!in_array($job['status'], ['tamamlandı', 'iptal', 'işlemde'], true)) {
                $upd = $pdo->prepare("UPDATE jobs SET status = 'işlemde' WHERE id = ?");
                $upd->execute([$job_id]);
            }

            header("Location: job_edit.php?id=" . $job_id);
            exit;
        } else {
            $password_error = "İş parolası hatalı.";
            $has_access     = false;
        }
    }
} else {
    // Parola gerekmiyorsa (teknisyen değilse veya durum 'yeni' değilse)
    $has_access = true;
}


// Teknisyen listesi (sadece admin + çağrı merkezi görecek)
$technicians = [];
if ($user['role'] == 1 || $user['role'] == 2) {
    $techStmt = $pdo->query("SELECT id, name FROM users WHERE role = 3 ORDER BY name");
    $technicians = $techStmt->fetchAll(PDO::FETCH_ASSOC);
}

// ---- ASIL KAYDETME İŞLEMLERİ ----
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !isset($_POST['password_check'])) {
     // FOTOĞRAF SİLME
    if (isset($_POST['delete_photo'])) {
        $photoId = intval($_POST['delete_photo']);

        // Foto bilgi çek
        $pStmt = $pdo->prepare("SELECT file_path FROM job_files WHERE id = ? AND job_id = ?");
        $pStmt->execute([$photoId, $job_id]);
        $photo = $pStmt->fetch(PDO::FETCH_ASSOC);

        if ($photo) {
            $fullPath = __DIR__ . '/' . $photo['file_path'];

            // Dosyayı sil
            if (file_exists($fullPath)) {
                unlink($fullPath);
            }

            // DB'den sil
            $del = $pdo->prepare("DELETE FROM job_files WHERE id = ?");
            $del->execute([$photoId]);
            system_log('file_delete', 'İşten fotoğraf silindi. Job ID: '.$job_id.' - File ID: '.$photoId);

        }

        // Sayfayı yenile
        header("Location: job_edit.php?id=" . $job_id);
        exit;
    }

   // Teknisyen parolayı doğrulamadan iş kaydı yapılamasın (sadece 'yeni' işler için)
if ($editing && $require_password && !$has_access) {
    die("Bu iş için iş parolası doğrulanmadan işlem yapılamaz.");
}


    // TAMAMLANDI + TEKNİSYEN → POST'u tamamen engelle
    if ($isCompletedTech) {
        die("Tamamlanmış bir işi teknisyen olarak değiştiremezsiniz.");
    }

    $title           = $_POST['title'] ?? '';
    $status          = $_POST['status'] ?? 'yeni';
    $price           = $_POST['price'] ?? null;
    $deposit         = $_POST['deposit'] ?? null; // Kapora
    $technician_note = $_POST['technician_note'] ?? null;

    // Tekrarlanan iş checkbox (yoksa 0, işaretliyse 1)
    $repeat_job = isset($_POST['repeat_job']) ? 1 : 0;

    // Yedek parça alanları
    $spare_part1       = $_POST['spare_part1'] ?? null;
    $spare_part2       = $_POST['spare_part2'] ?? null;
    $spare_part3       = $_POST['spare_part3'] ?? null;
    $extra_parts       = $_POST['extra_parts'] ?? [];
    $spare_parts_extra = null;
    if (is_array($extra_parts) && count($extra_parts) > 0) {
        $extra_parts_clean = array_filter(array_map('trim', $extra_parts));
        if (!empty($extra_parts_clean)) {
            $spare_parts_extra = implode("\n", $extra_parts_clean);
        }
    }

    // Müşteri bilgileri + müşteri notu
    if ($editing) {
        if ($user['role'] == 3) {
            // TEKNİSYEN → müşteri bilgileri & müşteri notu sabit
            $customer_name     = $job['customer_name'] ?? null;
            $customer_phone    = $job['customer_phone'] ?? null;
            $customer_phone2   = $job['customer_phone2'] ?? null;
            $customer_address  = $job['customer_address'] ?? null;
            $customer_district = $job['customer_district'] ?? null;
            $description       = $job['description'] ?? null;
        } else {
            // ADMIN / ÇAĞRI MERKEZİ
            $customer_name     = $_POST['customer_name'] ?? null;
            $customer_phone    = $_POST['customer_phone'] ?? null;
            $customer_phone2   = $_POST['customer_phone2'] ?? null;
            $customer_address  = $_POST['customer_address'] ?? null;
            $customer_district = $_POST['customer_district'] ?? null;
            $description       = $_POST['description'] ?? null;
        }
        // CİHAZ TÜRÜ: her rolde değişebilir
        $device_type = $_POST['device_type'] ?? ($job['device_type'] ?? null);
    } else {
        // YENİ İŞ
        $customer_name     = $_POST['customer_name'] ?? null;
        $customer_phone    = $_POST['customer_phone'] ?? null;
        $customer_phone2   = $_POST['customer_phone2'] ?? null;
        $customer_address  = $_POST['customer_address'] ?? null;
        $customer_district = $_POST['customer_district'] ?? null;
        $description       = $_POST['description'] ?? null;
        $device_type       = $_POST['device_type'] ?? null;
    }

    // Admin / Çağrı merkezi ise teknisyen seçebilir
    if ($user['role'] == 1 || $user['role'] == 2) {
        $technician_id = $_POST['technician_id'] ?: null;
    } else {
        $technician_id = $job['technician_id'] ?? $user['id'];
    }

    if ($editing) {
        // MEVCUT İŞİ GÜNCELLE (job_password DEĞİŞMİYOR)
        $stmt = $pdo->prepare("
            UPDATE jobs
            SET title = ?, description = ?, status = ?, technician_id = ?,
                customer_name = ?, customer_phone = ?, customer_phone2 = ?, customer_address = ?,
                customer_district = ?, device_type = ?,
                price = ?, deposit = ?, technician_note = ?,
                spare_part1 = ?, spare_part2 = ?, spare_part3 = ?, spare_parts_extra = ?,
                repeat_job = ?
            WHERE id = ?
        ");
        $stmt->execute([
            $title, $description, $status, $technician_id,
            $customer_name, $customer_phone, $customer_phone2, $customer_address,
            $customer_district, $device_type,
            $price, $deposit, $technician_note,
            $spare_part1, $spare_part2, $spare_part3, $spare_parts_extra,
            $repeat_job,
            $job_id
        ]);
        
        system_log('job_create', 'Yeni iş oluşturuldu. ID: '.$newJobId);


    } else {
        // YENİ İŞ OLUŞTUR
        if ($user['role'] == 1 || $user['role'] == 2) {

            $created_by = $user['id'];

            // 0–99999 arası rastgele iş parolası (5 haneli gösterelim)
            $randNum      = random_int(0, 99999);
            $job_password = str_pad((string)$randNum, 5, '0', STR_PAD_LEFT);

            $stmt = $pdo->prepare("
                INSERT INTO jobs
                (title, description, status, technician_id,
                 customer_name, customer_phone, customer_phone2, customer_address,
                 customer_district, device_type,
                 price, deposit, technician_note,
                 spare_part1, spare_part2, spare_part3, spare_parts_extra,
                 repeat_job, job_password, created_by)
                VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
            ");

            $stmt->execute([
                $title, $description, $status, $technician_id,
                $customer_name, $customer_phone, $customer_phone2, $customer_address,
                $customer_district, $device_type,
                $price, $deposit, $technician_note,
                $spare_part1, $spare_part2, $spare_part3, $spare_parts_extra,
                $repeat_job, $job_password, $created_by
            ]);

            $newJobId = $pdo->lastInsertId();
            system_log('job_create', 'Yeni iş oluşturuldu. ID: '.$newJobId);


         /* ==== TEKNİSYENE MAIL GÖNDER (SMTP + PHPMailer) ==== */
if (!empty($technician_id)) {

    // Teknisyen mail adresini çek
    $tStmt = $pdo->prepare("SELECT name, email FROM users WHERE id = ? AND role = 3");
    $tStmt->execute([$technician_id]);
    $tech = $tStmt->fetch(PDO::FETCH_ASSOC);

    if ($tech && !empty($tech['email'])) {

        $techEmail = $tech['email'];
        $subject   = "Yeni iş atandı (#{$newJobId})";

        $jobLink = "https://yetkilteknikservis.com/teknisyen/job_edit.php?id=" . $newJobId;

        $body =
"Merhaba {$tech['name']},

Size yeni bir iş atandı.

Müşteri   : " . ($customer_name ?: '-') . "
Telefon   : " . ($customer_phone ?: '-') . "
Cihaz     : " . ($title ?: '-') . "
Durum     : " . ($status ?: '-') . "
İş Parolası : " . ($job_password ?: '-') . "

Bu işin detaylarını görebilmek için önce yukarıdaki iş parolasını girmeniz gerekmektedir.

İş detayları için bağlantı:
{$jobLink}

Yetkil Teknik Servis";

        $sent = sendTechMail($techEmail, $tech['name'], $subject, $body);

        if (!$sent) {
            error_log("Teknisyen maili gönderilemedi: {$techEmail}");
        }
    }
}
/* ==== MAIL KISMI BİTTİ ==== */



            // Yeni işten sonra düzenleme sayfasına gönder (parolayı görebil)
           header("Location: job_created.php?id={$newJobId}&password={$job_password}");
exit;

            exit;
        } else {
            die("Yeni iş oluşturma yetkiniz yok.");
        }
    }


    // FOTOĞRAF YÜKLEME (sadece mevcut iş için)
    if ($editing && isset($_FILES['file']) && $_FILES['file']['error'] === UPLOAD_ERR_OK) {
        $uploadDir = __DIR__ . '/uploads';
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0777, true);
        }

        $filename   = time() . '_' . basename($_FILES['file']['name']);
        $targetPath = $uploadDir . '/' . $filename;
        if (move_uploaded_file($_FILES['file']['tmp_name'], $targetPath)) {
            $relativePath = 'uploads/' . $filename;

            $stmtFile = $pdo->prepare("INSERT INTO job_files (job_id, user_id, file_path, file_type) VALUES (?, ?, ?, ?)");
            $stmtFile->execute([$job_id, $user['id'], $relativePath, 'image']);
            system_log('file_upload', 'İşe fotoğraf yüklendi. Job ID: '.$job_id);

        }
    }

    // Düzenlemeden sonra listeye dön
    if ($editing) {
        header("Location: jobs.php");
        exit;
    }
}
?>
<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title><?php echo $editing ? "İşi Düzenle" : "Yeni İş"; ?></title>
    <link rel="stylesheet" href="style.css">
    <style>
    .job-photos {
        display: flex;
        flex-wrap: wrap;
        gap: 10px;
        margin-bottom: 15px;
    }
    .job-photo-item {
        border: 1px solid #ddd;
        padding: 4px;
        border-radius: 6px;
        background: #fafafa;
    }
    .job-photo-thumb {
        width: 140px;
        height: auto;
        border-radius: 4px;
        cursor: pointer;
        display: block;
    }

    /* Modal arkaplanı */
    .image-modal {
        display: none;              /* JS ile açacağız */
        position: fixed;
        z-index: 9999;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        overflow: auto;
        background-color: rgba(0,0,0,0.85);
    }

    /* Modal içindeki büyük resim */
    .image-modal-content {
        margin: 40px auto;
        display: block;
        max-width: 90%;
        max-height: 80vh;
        box-shadow: 0 0 15px rgba(0,0,0,0.5);
        border-radius: 8px;
    }

    /* Kapatma butonu */
    .image-modal-close {
        position: absolute;
        top: 15px;
        right: 30px;
        color: #fff;
        font-size: 32px;
        font-weight: bold;
        cursor: pointer;
    }

    .image-modal-close:hover {
        color: #ddd;
    }
    
    .job-photo-item {
    border:1px solid #ddd;
    padding: 6px;
    border-radius: 6px;
    background: #fafafa;
    position: relative;
    width: 150px;
}
.job-photo-item button {
    width:100%;
    font-size:12px;
}
</style>

</head>
<body>

<div class="container">
    <div class="card">

        <?php if ($require_password && !$has_access): ?>
            <h1>İş Parolası Girişi</h1>
            <p>Bu işin detaylarını görüntülemek için iş parolasını giriniz.</p>

            <?php if ($password_error): ?>
                <p style="color:red;"><?php echo htmlspecialchars($password_error); ?></p>
            <?php endif; ?>

            <form method="post">
                <input type="hidden" name="password_check" value="1">
                <label>İş Parolası:
                    <input type="text" name="job_password_input" required>
                </label>
                <br><br>
                <button type="submit" class="btn">Giriş Yap</button>
                <a class="btn" href="jobs.php">İptal</a>
            </form>

        <?php else: ?>

        <h1><?php echo $editing ? "İşi Düzenle" : "Yeni İş"; ?></h1>
        <p><a class="btn" href="jobs.php">← Listeye Dön</a></p>

        <form method="post" enctype="multipart/form-data">

            <!-- BAŞLIK -->
            <?php if ($isCompletedTech): ?>
                <p><strong>Marka / Cihaz:</strong><br>
                    <?php echo htmlspecialchars($job['title'] ?? ''); ?>
                </p>
            <?php else: ?>
                <label>Marka / Cihaz:
                    <input type="text" name="title" required
                           value="<?php echo htmlspecialchars($job['title'] ?? ''); ?>">
                </label>
            <?php endif; ?>

            <!-- MÜŞTERİ NOTU -->
            <?php if ($editing && $user['role'] == 3): ?>
                <p><strong>Müşteri Notu:</strong><br>
                    <?php echo nl2br(htmlspecialchars($job['description'] ?? '')); ?>
                </p>
            <?php else: ?>
                <label>Müşteri Notu:
                    <textarea name="description" rows="3"><?php
                        echo htmlspecialchars($job['description'] ?? '');
                    ?></textarea>
                </label>
            <?php endif; ?>

            <?php if ($user['role'] == 1 || $user['role'] == 2): ?>
                <h3>İş parolası:
                    <?php echo htmlspecialchars($job['job_password'] ?? '-'); ?>
                </h3>
            <?php endif; ?>

            <h3>Müşteri Bilgileri</h3>

            <?php if ($editing && $user['role'] == 3): ?>
                <!-- TEKNİSYEN → SADECE OKU -->
                <p><strong>Müşteri Adı Soyadı:</strong><br>
                    <?php echo htmlspecialchars($job['customer_name'] ?? '-'); ?>
                </p>

                <p><strong>Telefon 1:</strong><br>
                    <?php if (!empty($job['customer_phone'])): ?>
                        <a href="tel:+9<?php echo htmlspecialchars($job['customer_phone']); ?>">
                            <?php echo htmlspecialchars($job['customer_phone']); ?>
                        </a>
                    <?php else: ?>
                        -
                    <?php endif; ?>
                </p>

                <p><strong>Telefon 2:</strong><br>
                    <?php if (!empty($job['customer_phone2'])): ?>
                        <a href="tel:+9<?php echo htmlspecialchars($job['customer_phone2']); ?>">
                            <?php echo htmlspecialchars($job['customer_phone2']); ?>
                        </a>
                    <?php else: ?>
                        -
                    <?php endif; ?>
                </p>

                <p><strong>İl / İlçe:</strong><br>
                    <?php echo htmlspecialchars($job['customer_district'] ?? '-'); ?>
                </p>

                <p><strong>Adres:</strong><br>
                    <?php echo nl2br(htmlspecialchars($job['customer_address'] ?? '-')); ?>
                </p>

                <!-- Cihaz Türü: teknisyen, sadece tamamlanmamış işte değiştirebilsin -->
                <?php if ($isCompletedTech): ?>
                    <p><strong>Cihaz Türü:</strong><br>
                        <?php echo htmlspecialchars($job['device_type'] ?? '-'); ?>
                    </p>
                <?php else: ?>
                    <label>Cihaz Türü:
                        <input type="text" name="device_type"
                               value="<?php echo htmlspecialchars($job['device_type'] ?? ''); ?>">
                    </label>
                <?php endif; ?>

            <?php else: ?>
                <!-- ADMIN / ÇAĞRI MERKEZİ VEYA YENİ İŞ → DÜZENLEYEBİLİR -->
                <label>Müşteri Adı Soyadı:
                    <input type="text" name="customer_name"
                           value="<?php echo htmlspecialchars($job['customer_name'] ?? ''); ?>">
                </label>

                <label>Telefon 1:
                    <input type="text" name="customer_phone"
                           value="<?php echo htmlspecialchars($job['customer_phone'] ?? ''); ?>">
                </label>

                <label>Telefon 2:
                    <input type="text" name="customer_phone2"
                           value="<?php echo htmlspecialchars($job['customer_phone2'] ?? ''); ?>">
                </label>

                <?php if ($editing && !empty($job['customer_phone'])): ?>
                    <p><a class="btn" href="tel:+9<?php echo htmlspecialchars($job['customer_phone']); ?>">1. Numarayı Ara</a></p>
                <?php endif; ?>

                <label>İl / İlçe:
                    <input type="text" name="customer_district"
                           value="<?php echo htmlspecialchars($job['customer_district'] ?? ''); ?>">
                </label>

                <label>Adres:
                    <textarea name="customer_address" rows="3"><?php
                        echo htmlspecialchars($job['customer_address'] ?? '');
                    ?></textarea>
                </label>

                <label>Cihaz Türü:
                    <input type="text" name="device_type"
                           value="<?php echo htmlspecialchars($job['device_type'] ?? ''); ?>">
                </label>
            <?php endif; ?>

            <!-- TEKNİSYEN SEÇİMİ (sadece admin + çağrı merkezi) -->
            <?php if ($user['role'] == 1 || $user['role'] == 2): ?>
                <label>Teknisyen:
                    <select name="technician_id">
                        <option value="">Seçilmedi</option>
                        <?php
                        $currentTechId = $job['technician_id'] ?? null;
                        foreach ($technicians as $t) {
                            $sel = ($currentTechId == $t['id']) ? 'selected' : '';
                            echo "<option value=\"{$t['id']}\" $sel>" . htmlspecialchars($t['name']) . "</option>";
                        }
                        ?>
                    </select>
                </label>
            <?php endif; ?>
<?php
// Bu işin fotoğraflarını çek
if ($editing) {
    $fileStmt = $pdo->prepare("SELECT id, file_path FROM job_files WHERE job_id = ?");
    $fileStmt->execute([$job_id]);
    $files = $fileStmt->fetchAll(PDO::FETCH_ASSOC);

    if (!empty($files)) { ?>
        <h3>Yüklenen Fotoğraflar</h3>
        <div class="job-photos">
            <?php foreach ($files as $f): 
                $src = htmlspecialchars($f['file_path']);
            ?>
                <div class="job-photo-item">
                    <img src="<?php echo $src; ?>" 
                         class="job-photo-thumb" 
                         data-full="<?php echo $src; ?>">

                    <!-- Ayrı form YOK; ana formun içinde ekstra submit butonu var -->
                    <?php if (($job['status'] ?? null) !== 'tamamlandı'): ?>
    <button type="submit"
            name="delete_photo"
            value="<?php echo $f['id']; ?>"
            class="btn"
            style="background:#d9534f; color:#fff; padding:4px 8px; border-radius:5px; border:none; cursor:pointer; margin-top:6px;"
            onclick="return confirm('Bu fotoğraf silinsin mi?');">
        Fotoğrafı Sil
    </button>
<?php endif; ?>

                </div>
            <?php endforeach; ?>
        </div>
    <?php }
}
?>



            <?php if ($editing): ?>
                <h3>Değişen Yedek Parçalar</h3>

                <?php if ($isCompletedTech): ?>
                    <p><strong>1. Yedek Parça:</strong><br>
                        <?php echo htmlspecialchars($job['spare_part1'] ?? '-'); ?>
                    </p>
                    <p><strong>2. Yedek Parça:</strong><br>
                        <?php echo htmlspecialchars($job['spare_part2'] ?? '-'); ?>
                    </p>
                    <p><strong>3. Yedek Parça:</strong><br>
                        <?php echo htmlspecialchars($job['spare_part3'] ?? '-'); ?>
                    </p>
                    <?php if (!empty($extra_parts_existing)): ?>
                        <p><strong>Ek Yedek Parçalar:</strong><br>
                            <?php foreach ($extra_parts_existing as $p): ?>
                                <?php if (trim($p) === '') continue; ?>
                                <?php echo htmlspecialchars($p) . "<br>"; ?>
                            <?php endforeach; ?>
                        </p>
                    <?php endif; ?>
                <?php else: ?>
                    <label><h4>1. Yedek Parça:</h4>
                        <input type="text" name="spare_part1"
                               value="<?php echo htmlspecialchars($job['spare_part1'] ?? ''); ?>">
                    </label>

                    <label>2. Yedek Parça:
                        <input type="text" name="spare_part2"
                               value="<?php echo htmlspecialchars($job['spare_part2'] ?? ''); ?>">
                    </label>

                    <label>3. Yedek Parça:
                        <input type="text" name="spare_part3"
                               value="<?php echo htmlspecialchars($job['spare_part3'] ?? ''); ?>">
                    </label>

                    <div id="extraPartsContainer">
                        <?php if (!empty($extra_parts_existing)): ?>
                            <?php foreach ($extra_parts_existing as $p): ?>
                                <?php if (trim($p) === '') continue; ?>
                                <input type="text" name="extra_parts[]" value="<?php echo htmlspecialchars($p); ?>" style="margin-bottom:6px;">
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                    <button type="button" class="btn" style="margin-top:6px;" onclick="addExtraPart()">+ Ek Parça Alanı Ekle</button>
                <?php endif; ?>

                <?php if (!$isCompletedTech): ?>
                    <h3>Fotoğraf (Tamamlandı → zorunlu)</h3>
                    <input type="file" name="file" id="file">
                <?php endif; ?>

                <h3>Teknisyen Notu ve Fiyat</h3>

                <?php if ($isCompletedTech): ?>
                    <p><strong>Teknisyen Rapor / Not:</strong><br>
                        <?php echo nl2br(htmlspecialchars($job['technician_note'] ?? '-')); ?>
                    </p>
                    <p><strong>Kapora (TL):</strong><br>
                        <?php echo htmlspecialchars($job['deposit'] ?? '-'); ?>
                    </p>
                    <p><strong>Fiyat (TL):</strong><br>
                        <?php echo htmlspecialchars($job['price'] ?? '-'); ?>
                    </p>
                <?php else: ?>
                    <label>Teknisyen Rapor / Not:
                        <textarea name="technician_note" rows="4"><?php
                            echo htmlspecialchars($job['technician_note'] ?? '');
                        ?></textarea>
                    </label>

                    <label>Kapora (TL):
                        <input type="number" step="0.01" name="deposit"
                               value="<?php echo htmlspecialchars($job['deposit'] ?? ''); ?>">
                    </label>

                    <label>Fiyat (TL):
                        <input type="number" step="0.01" name="price"
                               value="<?php echo htmlspecialchars($job['price'] ?? ''); ?>">
                    </label>
                <?php endif; ?>
            <?php endif; ?>

            <!-- Tekrarlanan İş Checkbox -->
           <div style="margin-top:10px; margin-bottom:10px;">
    <?php if ($isCompletedTech): ?>
        <?php if (!empty($job['repeat_job'])): ?>
            <p><strong>Tekrarlanan İş:</strong> Evet</p>
        <?php endif; ?>
    <?php else: ?>
        <label>
            <input type="checkbox" name="repeat_job" value="1"
                <?php
                $repeatChecked = ($job && !empty($job['repeat_job'])) ? 'checked' : '';
                echo $repeatChecked;
                ?>>
            Tekrarlanan İş
        </label>
    <?php endif; ?>
</div>


            <!-- DURUM -->
            <label><h3>Durum:</h3>
                <?php if ($isCompletedTech): ?>
                    <p><strong><?php echo htmlspecialchars($job['status'] ?? 'tamamlandı'); ?></strong></p>
                <?php else: ?>
                    <select name="status">
                        <?php
                        $currentStatus = $job['status'] ?? 'yeni';
                        $statuses = ['yeni', 'atandı', 'yolda', 'işlemde', 'parça_bekleniyor', 'tamamlandı', 'iptal'];
                        foreach ($statuses as $st) {
                            $sel = ($st == $currentStatus) ? 'selected' : '';
                            echo "<option value=\"$st\" $sel>$st</option>";
                        }
                        ?>
                    </select>
                <?php endif; ?>
            </label>

            <?php if (!$isCompletedTech): ?>
                <button type="submit" class="btn">Kaydet</button>
            <?php endif; ?>

        </form>

        <?php endif; // parola erişim endif ?>

    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {

    var form         = document.querySelector('form');
    var statusSelect = document.querySelector('select[name="status"]');
    var fileInput    = document.getElementById('file');
    var noteField    = document.querySelector('textarea[name="technician_note"]');

    if (form) {
        form.addEventListener('submit', function (e) {

            if (!statusSelect) return; // tamamlandı teknisyende select yok

            var status  = statusSelect.value;
            var hasFile = fileInput && fileInput.files && fileInput.files.length > 0;
            var noteVal = noteField ? noteField.value.trim() : '';

            // Tamamlandı → foto zorunlu
            if (status === 'tamamlandı' && fileInput && !hasFile) {
                alert("Tamamlandı durumuna geçerken en az 1 fotoğraf yüklemeniz gerekiyor.");
                e.preventDefault();
                return;
            }

            // Parça bekleniyor → teknisyen notu zorunlu
            if (status === 'parça_bekleniyor' && noteField && noteVal === '') {
                alert("Parça bekleniyor durumunda teknisyen notu zorunludur.");
                e.preventDefault();
                return;
            }
        });
    }

    // ===== Fotoğraf modalı =====
    var modal      = document.getElementById('imageModal');
    var modalImg   = document.getElementById('imageModalImg');
    var closeBtn   = document.querySelector('.image-modal-close');
    var thumbs     = document.querySelectorAll('.job-photo-thumb');

    if (modal && modalImg && closeBtn && thumbs.length > 0) {

        thumbs.forEach(function(img) {
            img.addEventListener('click', function () {
                var fullSrc = img.getAttribute('data-full') || img.getAttribute('src');
                modalImg.setAttribute('src', fullSrc);
                modal.style.display = 'block';
            });
        });

        closeBtn.addEventListener('click', function () {
            modal.style.display = 'none';
            modalImg.setAttribute('src', '');
        });

        modal.addEventListener('click', function (e) {
            // arka plana tıklandığında da kapat
            if (e.target === modal) {
                modal.style.display = 'none';
                modalImg.setAttribute('src', '');
            }
        });

        document.addEventListener('keyup', function (e) {
            if (e.key === 'Escape' && modal.style.display === 'block') {
                modal.style.display = 'none';
                modalImg.setAttribute('src', '');
            }
        });
    }

});

// Ek yedek parça inputu
function addExtraPart() {
    var container = document.getElementById('extraPartsContainer');
    if (!container) return;

    var input = document.createElement('input');
    input.type = 'text';
    input.name = 'extra_parts[]';
    input.style.marginBottom = '6px';
    input.placeholder = 'Ek yedek parça';
    container.appendChild(input);
}

document.addEventListener('input', function (e) {
    if (e.target.tagName.toLowerCase() === 'input' && e.target.type === 'text') {
        let value = e.target.value;

        // Kelimelerin baş harfini büyüt
        value = value.replace(/\b\w/g, function (char) {
            return char.toUpperCase();
        });

        e.target.value = value;
    }
});
</script>
<!-- Fotoğraf büyük gösterim modali -->
<div id="imageModal" class="image-modal">
    <span class="image-modal-close">&times;</span>
    <img class="image-modal-content" id="imageModalImg" alt="Fotoğraf">
</div>
