<?php
require_once __DIR__ . '/../includes/config.php';
yetkili_mi(['cari_yonetimi', 'cari_goruntuleme']);

$sayfa_baslik = __("customer_management");
$paraBirimi = getParaBirimiSembolu();

// Cari ekleme
if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['cari_ekle'])) {
    if(!csrf_token_dogrula($_POST['csrf_token'] ?? '')) {
        $_SESSION['hata'] = __("invalid_form_submission");
        header("Location: cariler.php");
        exit();
    }

    $ad_soyad = temizle($_POST['ad_soyad']);
    $telefon = temizle($_POST['telefon']);
    $eposta = temizle($_POST['eposta']);
    $adres = temizle($_POST['adres']);
    $grup_id = filter_input(INPUT_POST, 'grup_id', FILTER_VALIDATE_INT);

     // Basit doğrulama
     $hatalar = [];
     if (empty($ad_soyad)) $hatalar[] = __("customer_name_required");
     if (empty($grup_id)) $hatalar[] = __("customer_group_required");

    if (empty($hatalar)) {
        try {
            // Başlangıç bakiyeleri 0 olacak
            $stmt = $db->prepare("INSERT INTO cariler (sirket_id, ad_soyad, telefon, eposta, adres, grup_id, toplam_borc, toplam_alacak, bakiye, olusturulma_tarihi)
                                VALUES (?, ?, ?, ?, ?, ?, 0.00, 0.00, 0.00, NOW())");
            $stmt->execute([$_SESSION['aktif_sirket_id'], $ad_soyad, $telefon, $eposta, $adres, $grup_id]);

            $_SESSION['mesaj'] = __("customer_added_success");
            header("Location: cariler.php");
            exit();
        } catch(PDOException $e) {
            error_log("Cari ekleme hatası: " . $e->getMessage());
             // Duplicate entry hatası kontrolü (ad_soyad unique değilse bu gereksiz)
            // if ($e->getCode() == 23000) { // Integrity constraint violation
            //     $_SESSION['hata'] = "Bu isimde bir cari zaten mevcut olabilir.";
            // } else {
                 $_SESSION['hata'] = __("error_adding_customer") . ": " . $e->getMessage();
            // }
            $_SESSION['form_verileri_cari_ekle'] = $_POST; // Form verilerini sakla
            header("Location: cariler.php");
            exit();
        }
     } else {
         $_SESSION['form_hatalari_cari_ekle'] = $hatalar;
         $_SESSION['form_verileri_cari_ekle'] = $_POST;
         header("Location: cariler.php");
         exit();
     }
}

// Carileri listeleme
try {
    $aktif_sirket_id = $_SESSION['aktif_sirket_id'];

    // Carileri listeleme
    $stmt_cariler = $db->prepare("
        SELECT c.*, g.grup_adi
        FROM cariler c
        LEFT JOIN cari_gruplari g ON c.grup_id = g.id
        WHERE c.sirket_id = ?
        ORDER BY c.ad_soyad
    ");
    $stmt_cariler->execute([$aktif_sirket_id]);
    $cariler = $stmt_cariler->fetchAll(PDO::FETCH_ASSOC);

    // Cari gruplarını listeleme
    $stmt_gruplar = $db->prepare("SELECT * FROM cari_gruplari WHERE sirket_id = ? ORDER BY grup_adi");
    $stmt_gruplar->execute([$aktif_sirket_id]);
    $cari_gruplari = $stmt_gruplar->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $e) {
    error_log("Cari listeleme hatası: " . $e->getMessage());
     $_SESSION['hata'] = __("error_loading_customer_list");
    $cariler = [];
    $cari_gruplari = [];
}

$csrf_token = csrf_token_olustur();
// Hataları ve form verilerini al (varsa)
$form_hatalari = $_SESSION['form_hatalari_cari_ekle'] ?? [];
$form_verileri = $_SESSION['form_verileri_cari_ekle'] ?? [];
unset($_SESSION['form_hatalari_cari_ekle'], $_SESSION['form_verileri_cari_ekle']);

// Özet istatistikler
$cari_sayisi = count($cariler);
$toplam_musteri_borcu = 0.0;
$toplam_bizim_borcumuz = 0.0;
$toplam_net_bakiye = 0.0;

foreach ($cariler as $cari_row) {
    $musteri_borcu = (float)($cari_row['toplam_borc'] ?? 0);
    $bizim_borcumuz = (float)($cari_row['toplam_alacak'] ?? 0);
    $net_bakiye = $musteri_borcu - $bizim_borcumuz;
    
    // Müşteri borçları (bize olan borçlar) - sadece pozitif değerler
    if ($musteri_borcu > 0) {
        $toplam_musteri_borcu += $musteri_borcu;
    }
    
    // Tedarikçi borçlarımız (tedarikçiye olan borçlarımız)
    // Negatif müşteri borcu = bizim tedarikçiye olan borcumuz
    if ($musteri_borcu < 0) {
        $toplam_bizim_borcumuz += abs($musteri_borcu);
    }
    
    // Ayrıca toplam_alacak kolonundaki pozitif değerler de tedarikçi borcumuz
    if ($bizim_borcumuz > 0) {
        $toplam_bizim_borcumuz += $bizim_borcumuz;
    }
    
    $toplam_net_bakiye += $net_bakiye;
}

?>
<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= __("app_name") ?> - <?= temizle($sayfa_baslik) ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <style>
        .customer-avatar {
            width: 46px;
            height: 46px;
            border-radius: 50%;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
            font-size: 1.15rem;
            color: #fff;
            flex-shrink: 0;
        }
        .customer-meta {
            font-size: 0.85rem;
            color: var(--bs-secondary-color);
        }
        .customer-meta .meta-item {
            display: inline-flex;
            align-items: center;
            gap: 0.35rem;
            margin-right: 1rem;
        }
        .customer-meta .meta-item:last-child {
            margin-right: 0;
        }
        .customer-meta .meta-item i {
            font-size: 0.95rem;
            color: var(--bs-secondary-color);
        }
        .balance-chip {
            border-radius: 999px;
            padding: 0.35rem 0.75rem;
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
        }
        .highlight-row:hover {
            background-color: rgba(13, 110, 253, 0.03);
        }
        #cariTable th:last-child,
        #cariTable td:last-child {
            white-space: nowrap;
            width: 1%;
        }
        @media (max-width: 767.98px) {
            .customer-meta {
                display: flex;
                flex-direction: column;
                gap: 0.25rem;
            }
            .customer-meta .meta-item {
                margin-right: 0;
            }
        }
    </style>
</head>
<body>
    <?php include __DIR__ . '/../includes/navbar.php'; ?>

    <div class="container mt-4">
        <div class="d-flex flex-column flex-lg-row justify-content-between align-items-lg-center mb-3 gap-3">
            <div>
                <h2 class="mb-0"><i class="bi bi-people me-2"></i> <?= temizle($sayfa_baslik) ?></h2>
                <small class="text-muted"><?= __("customer_management_description") ?></small>
            </div>
            <div class="d-flex gap-2">
                <button class="btn btn-primary" type="button" data-bs-toggle="collapse" data-bs-target="#collapseCariEkle" aria-expanded="false" aria-controls="collapseCariEkle">
                    <i class="bi bi-plus-circle me-1"></i> <?= __("add_new_customer") ?>
                </button>
            </div>
        </div>

        <!-- Özet kartları -->
        <div class="row g-3 mb-3">
            <div class="col-12 col-md-3">
                <div class="card text-white bg-primary shadow-sm h-100">
                    <div class="card-body">
                        <div class="d-flex align-items-center justify-content-between">
                            <div>
                                <div class="opacity-75"><?= __("total_customers") ?></div>
                                <div class="fs-4 fw-bold"><?= number_format($cari_sayisi) ?></div>
                            </div>
                            <i class="bi bi-person-lines-fill fs-1"></i>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-12 col-md-3">
                <div class="card text-white bg-danger shadow-sm h-100">
                    <div class="card-body">
                        <div class="d-flex align-items-center justify-content-between">
                            <div>
                                <div class="opacity-75"><?= __("total_customer_debt") ?></div>
                                <div class="fs-4 fw-bold"><?= number_format($toplam_musteri_borcu, 2, ',', '.') ?> <?= $paraBirimi ?></div>
                                <div class="small text-white-50"><?= __("only_positive_debts") ?></div>
                            </div>
                            <i class="bi bi-arrow-down-right fs-1"></i>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-12 col-md-3">
                <div class="card text-white bg-success shadow-sm h-100">
                    <div class="card-body">
                        <div class="d-flex align-items-center justify-content-between">
                            <div>
                                <div class="opacity-75"><?= __("total_supplier_debt") ?></div>
                                <div class="fs-4 fw-bold"><?= number_format($toplam_bizim_borcumuz, 2, ',', '.') ?> <?= $paraBirimi ?></div>
                                <div class="small text-white-50"><?= __("only_positive_debts") ?></div>
                            </div>
                            <i class="bi bi-arrow-up-right fs-1"></i>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-12 col-md-3">
                <div class="card text-white bg-info shadow-sm h-100">
                    <div class="card-body">
                        <div class="d-flex align-items-center justify-content-between">
                            <div>
                                <div class="opacity-75"><?= __("net_balance") ?></div>
                                <div class="fs-4 fw-bold"><?= number_format($toplam_net_bakiye, 2, ',', '.') ?> <?= $paraBirimi ?></div>
                                <div class="small text-white-50"><?= __("total_of_all_customers") ?></div>
                            </div>
                            <i class="bi bi-calculator fs-1"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <hr>

        <!-- Bakiye Açıklaması -->
        <div class="alert alert-info mb-3">
            <h6 class="alert-heading"><i class="bi bi-info-circle me-2"></i><?= __("balance_summary") ?></h6>
           <hr class="my-2">
            <div class="row">
                <div class="col-md-12">
                    <strong><?= __("signs") ?>:</strong> 
                    <span class="badge bg-danger"><?= __("debtor_short") ?></span> = <?= __("debtor") ?>, 
                    <span class="badge bg-success"><?= __("creditor_short") ?></span> = <?= __("creditor") ?><br>
                  </div>
            </div>
        </div>

        <?php if (!empty($form_hatalari)): ?>
             <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <strong><i class="bi bi-exclamation-triangle-fill me-2"></i> <?= __("please_fix_errors") ?>:</strong>
                <ul>
                    <?php foreach ($form_hatalari as $hata): ?>
                        <li><?= htmlspecialchars($hata) ?></li>
                    <?php endforeach; ?>
                </ul>
                 <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        <?php endif; ?>

        <div class="collapse mb-4" id="collapseCariEkle">
            <div class="card card-body shadow-sm border-0">
                 <h5 class="card-title mb-3"><i class="bi bi-person-plus me-2"></i><?= __("new_customer_information") ?></h5>
                 <form method="post">
                    <input type="hidden" name="csrf_token" value="<?= $csrf_token ?>">
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label for="ad_soyad" class="form-label"><?= __("customer_name") ?> <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="ad_soyad" name="ad_soyad" required
                                    value="<?= htmlspecialchars($form_verileri['ad_soyad'] ?? '', ENT_QUOTES) ?>">
                        </div>
                        <div class="col-md-6">
                            <label for="telefon" class="form-label"><?= __("phone") ?></label>
                            <input type="tel" class="form-control" id="telefon" name="telefon"
                                    value="<?= htmlspecialchars($form_verileri['telefon'] ?? '', ENT_QUOTES) ?>">
                        </div>
                        <div class="col-md-6">
                            <label for="eposta" class="form-label"><?= __("email") ?></label>
                            <input type="email" class="form-control" id="eposta" name="eposta"
                                    value="<?= htmlspecialchars($form_verileri['eposta'] ?? '', ENT_QUOTES) ?>">
                        </div>
                        <div class="col-md-6">
                            <label for="grup_id" class="form-label"><?= __("customer_group") ?> <span class="text-danger">*</span></label>
                            <select class="form-select" id="grup_id" name="grup_id" required>
                                <option value="">-- <?= __("select_group") ?> --</option>
                                <?php foreach($cari_gruplari as $grup): ?>
                                    <option value="<?= $grup['id'] ?>" <?= (isset($form_verileri['grup_id']) && $form_verileri['grup_id'] == $grup['id']) ? 'selected' : '' ?>>
                                        <?= temizle($grup['grup_adi']) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                         <div class="col-md-6">
                            <label for="adres" class="form-label"><?= __("address") ?></label>
                            <textarea class="form-control" id="adres" name="adres" rows="1"><?= htmlspecialchars($form_verileri['adres'] ?? '', ENT_QUOTES) ?></textarea>
                        </div>
                        <div class="col-12 d-flex gap-2">
                             <button type="submit" name="cari_ekle" class="btn btn-success">
                                <i class="bi bi-save me-1"></i> <?= __("save") ?>
                            </button>
                             <button type="button" class="btn btn-outline-secondary" data-bs-toggle="collapse" data-bs-target="#collapseCariEkle"><?= __("cancel") ?></button>
                        </div>
                    </div>
                </form>
            </div>
        </div>

        <div class="card shadow-sm">
            <div class="card-header">
                <div class="d-flex flex-column flex-md-row align-items-md-center justify-content-between gap-2">
                    <h5 class="mb-0"><i class="bi bi-list-ul me-2"></i> <?= __("customer_list") ?></h5>
                    <div class="input-group shadow-sm rounded-pill overflow-hidden" style="max-width: 360px;">
                        <span class="input-group-text bg-white border-0"><i class="bi bi-search"></i></span>
                        <input type="text" id="cariSearch" class="form-control border-0 shadow-none" placeholder="<?= __("customer_search_placeholder") ?>" aria-label="<?= __("customer_search_placeholder") ?>">
                    </div>
                </div>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-hover table-striped align-middle mb-0" id="cariTable">
                        <thead class="table-light">
                            <tr>
                                <th><?= __("customer_name") ?></th>
                                <th><?= __("phone") ?> &amp; <?= __("email") ?></th>
                                <th><?= __("group") ?></th>
                                <th class="text-end"><?= __("customer_debt_to_us") ?></th>
                                <th class="text-end"><?= __("our_debt_to_supplier") ?></th>
                                <th class="text-end"><?= __("net_balance") ?></th>
                                <th class="text-center"><?= __("actions") ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($cariler)): ?>
                                <tr>
                                    <td colspan="7" class="text-center text-muted py-3"><?= __("no_customers_found") ?></td>
                                </tr>
                            <?php else: ?>
                                <?php foreach($cariler as $cari):
                                    // Bakiye hesaplaması düzeltildi
                                    // Müşterinin borcu (bize olan borcu) - toplam_borc
                                    // Bizim borcumuz (tedarikçiye olan borcumuz) - toplam_alacak
                                    // Net bakiye = Müşterinin borcu - Bizim borcumuz
                                    // Pozitif: Müşteri bize borçlu (B)
                                    // Negatif: Biz müşteriye borçluyuz (A)
                                    $musteri_borcu = $cari['toplam_borc'] ?? 0.0;
                                    $bizim_borcumuz = $cari['toplam_alacak'] ?? 0.0;
                                    $net_bakiye = $musteri_borcu - $bizim_borcumuz;

                                    // Bakiye durumu belirleme
                                    $bakiye_durumu = '';
                                    $bakiye_renk = '';
                                    if ($net_bakiye > 0) {
                                        $bakiye_durumu = 'B'; // Borçlu (Müşteri bize borçlu)
                                        $bakiye_renk = 'text-danger';
                                    } elseif ($net_bakiye < 0) {
                                        $bakiye_durumu = 'A'; // Alacaklı (Biz müşteriye borçluyuz)
                                        $bakiye_renk = 'text-success';
                                    } else {
                                        $bakiye_durumu = '-'; // Sıfır bakiye
                                        $bakiye_renk = 'text-muted';
                                    }
                                    $ad_soyad = $cari['ad_soyad'] ?? '';
                                    $avatar_harf = mb_substr(trim($ad_soyad), 0, 1, 'UTF-8');
                                    $avatar_harf = $avatar_harf ? mb_strtoupper($avatar_harf, 'UTF-8') : '?';
                                    $avatar_renk = $net_bakiye > 0 ? 'bg-danger' : ($net_bakiye < 0 ? 'bg-success' : 'bg-secondary');
                                    $telefon_deger = trim($cari['telefon'] ?? '');
                                    $eposta_deger = trim($cari['eposta'] ?? '');
                                    $telefon_temiz = $telefon_deger !== '' ? temizle($telefon_deger) : '';
                                    $eposta_temiz = $eposta_deger !== '' ? temizle($eposta_deger) : '';
                                    $net_balance_chip_class = $net_bakiye > 0 ? 'bg-danger-subtle text-danger' : ($net_bakiye < 0 ? 'bg-success-subtle text-success' : 'bg-light text-muted');
                                    $badge_class = $bakiye_durumu === 'B' ? 'bg-danger text-white' : ($bakiye_durumu === 'A' ? 'bg-success text-white' : 'bg-secondary text-white');
                                ?>
                                <tr class="highlight-row">
                                    <td>
                                        <div class="d-flex align-items-center gap-3">
                                            <div class="customer-avatar <?= $avatar_renk ?>">
                                                <?= htmlspecialchars($avatar_harf, ENT_QUOTES, 'UTF-8') ?>
                                            </div>
                                            <div class="fw-semibold"><?= temizle($ad_soyad) ?></div>
                                        </div>
                                    </td>
                                    <td>
                                        <div class="customer-meta">
                                            <span class="meta-item">
                                                <i class="bi bi-telephone"></i>
                                                <?php if ($telefon_temiz): ?>
                                                    <?= $telefon_temiz ?>
                                                <?php else: ?>
                                                    <span class="text-muted">-</span>
                                                <?php endif; ?>
                                            </span>
                                            <span class="meta-item">
                                                <i class="bi bi-envelope"></i>
                                                <?php if ($eposta_temiz): ?>
                                                    <?= $eposta_temiz ?>
                                                <?php else: ?>
                                                    <span class="text-muted">-</span>
                                                <?php endif; ?>
                                            </span>
                                        </div>
                                    </td>
                                    <td>
                                        <?php if (!empty($cari['grup_adi'])): ?>
                                            <span class="badge rounded-pill bg-secondary-subtle text-secondary-emphasis border border-secondary-subtle px-3 py-2"><?= temizle($cari['grup_adi']) ?></span>
                                        <?php else: ?>
                                            <span class="text-muted">-</span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="text-end">
                                        <span class="d-inline-flex align-items-center gap-2 text-danger fw-semibold">
                                            <i class="bi bi-arrow-down-right-circle"></i>
                                            <?= number_format($musteri_borcu, 2, ',', '.') ?> <?= $paraBirimi ?>
                                        </span>
                                    </td>
                                    <td class="text-end">
                                        <span class="d-inline-flex align-items-center gap-2 text-success fw-semibold">
                                            <i class="bi bi-arrow-up-right-circle"></i>
                                            <?= number_format($bizim_borcumuz, 2, ',', '.') ?> <?= $paraBirimi ?>
                                        </span>
                                    </td>
                                    <td class="text-end">
                                        <div class="balance-chip <?= $net_balance_chip_class ?>">
                                            <span class="fw-semibold"><?= number_format(abs($net_bakiye), 2, ',', '.') ?> <?= $paraBirimi ?></span>
                                            <span class="badge <?= $badge_class ?>">
                                                <?= $bakiye_durumu ?>
                                            </span>
                                        </div>
                                    </td>
                                    <td class="text-center">
                                        <div class="btn-group btn-group-sm" role="group">
                                            <a href="cari_detay.php?id=<?= $cari['id'] ?>" class="btn btn-outline-primary" title="<?= __("details_statement") ?>"><i class="bi bi-eye"></i></a>
                                            <a href="cari_duzenle.php?id=<?= $cari['id'] ?>" class="btn btn-outline-warning" title="<?= __("edit") ?>"><i class="bi bi-pencil"></i></a>
                                            <a href="cari_sil.php?id=<?= $cari['id'] ?>&csrf_token=<?= $csrf_token ?>"
                                               class="btn btn-outline-danger" title="<?= __("delete") ?>"
                                               onclick="return confirm('<?= addslashes(__("delete_customer_confirm")) ?>')">
                                                <i class="bi bi-trash"></i>
                                            </a>
                                        </div>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

	<?php include __DIR__ . '/../includes/footer.php'; ?>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
    // Basit tablo arama filtresi
    document.getElementById('cariSearch')?.addEventListener('input', function() {
        const term = this.value.toLowerCase();
        const rows = document.querySelectorAll('#cariTable tbody tr');
        rows.forEach(row => {
            const text = row.innerText.toLowerCase();
            row.style.display = text.includes(term) ? '' : 'none';
        });
    });
    </script>
</body>
</html>