<?php
// 1. AYARLAR
session_start();
require_once 'system/db.php';

// Güvenlik
if (!isset($_SESSION['is_logged_in']) || $_SESSION['is_logged_in'] !== true) {
    header("Location: login.php");
    exit;
}

// --- CRM DATASINI HAZIRLA (JS İÇİN) ---
// Tüm müşterileri çekip JSON formatına çeviriyoruz ki JS ile anlık doldurabilelim.
$all_customers = $db->query("SELECT * FROM customers ORDER BY name ASC")->fetchAll(PDO::FETCH_ASSOC);
$json_customers = json_encode($all_customers);
// --------------------------------------

$mesaj = "";
$mesaj_tur = "";

// 2. FATURA KAYDETME İŞLEMİ
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    
    // Form Verileri
    $invoice_no     = trim($_POST['invoice_no']);
    $cust_name      = trim($_POST['customer_name']);
    $comp_name      = trim($_POST['company_name']);
    $cust_email     = trim($_POST['customer_email']);
    $cust_phone     = trim($_POST['customer_phone']);
    $cust_landline  = trim($_POST['customer_landline']);
    $cust_addr      = trim($_POST['customer_address']);
    
    $issue_date     = $_POST['issue_date'];
    $due_date       = $_POST['due_date'];
    $status         = $_POST['status'];
    
    $descriptions = $_POST['desc']; 
    $quantities   = $_POST['qty']; 
    $prices       = $_POST['price'];

    // Validasyon
    if (empty($cust_name)) {
        $mesaj = "Hata: Müşteri Adı zorunludur.";
        $mesaj_tur = "danger";
    }
    elseif (empty($cust_email) && empty($cust_phone) && empty($cust_landline)) {
        $mesaj = "Hata: En az bir iletişim bilgisi (Email, Cep veya Sabit Hat) girmelisiniz.";
        $mesaj_tur = "danger";
    }
    else {
        
        try {
            $db->beginTransaction();

            // --- CRM OTOMATİK KAYIT SİSTEMİ ---
            // Bu isimde veya bu mailde müşteri var mı?
            $check_crm = $db->prepare("SELECT id FROM customers WHERE name = :name OR (email = :email AND email != '')");
            $check_crm->execute(['name' => $cust_name, 'email' => $cust_email]);
            $crm_exist = $check_crm->fetch();

            if (!$crm_exist) {
                // Yoksa: CRM'e YENİ EKLE
                $crm_sql = "INSERT INTO customers (name, company_name, email, phone, landline, address) VALUES (:name, :comp, :email, :phone, :land, :addr)";
                $crm_stmt = $db->prepare($crm_sql);
                $crm_stmt->execute([
                    'name' => $cust_name, 'comp' => $comp_name, 'email' => $cust_email, 
                    'phone' => $cust_phone, 'land' => $cust_landline, 'addr' => $cust_addr
                ]);
            } else {
                // Varsa: İstenirse bilgileri güncellenebilir (Şimdilik dokunmuyoruz)
            }
            // ----------------------------------

            // 1. Faturayı Ekle
            $grand_total = 0;
            for ($i = 0; $i < count($quantities); $i++) {
                $grand_total += floatval($quantities[$i]) * floatval($prices[$i]);
            }

            $sql = "INSERT INTO invoices (invoice_no, customer_name, company_name, customer_email, customer_phone, customer_landline, customer_address, total_amount, issue_date, due_date, status) 
                    VALUES (:no, :name, :comp, :email, :phone, :land, :addr, :total, :issue, :due, :stat)";
            
            $stmt = $db->prepare($sql);
            $stmt->execute([
                'no' => $invoice_no, 'name' => $cust_name, 'comp' => $comp_name, 'email' => $cust_email,
                'phone' => $cust_phone, 'land' => $cust_landline, 'addr' => $cust_addr,
                'total' => $grand_total, 'issue' => $issue_date, 'due' => $due_date, 'stat' => $status
            ]);
            
            $invoice_id = $db->lastInsertId();

            // 2. Kalemleri Ekle
            $sql_item = "INSERT INTO invoice_items (invoice_id, description, quantity, unit_price, total_price) VALUES (:id, :desc, :qty, :price, :total)";
            $stmt_item = $db->prepare($sql_item);

            for ($i = 0; $i < count($descriptions); $i++) {
                if(!empty($descriptions[$i])) {
                    $row_total = floatval($quantities[$i]) * floatval($prices[$i]);
                    $stmt_item->execute([
                        'id' => $invoice_id, 'desc' => $descriptions[$i], 'qty' => $quantities[$i], 
                        'price' => $prices[$i], 'total' => $row_total
                    ]);
                }
            }

            $db->commit();
            $mesaj = "Fatura oluşturuldu ve müşteri sisteme işlendi!";
            $mesaj_tur = "success";

        } catch (Exception $e) {
            $db->rollBack();
            $mesaj = "Hata: " . $e->getMessage();
            $mesaj_tur = "danger";
        }
    }
}
$rand_no = "FTR-" . date("Y") . "-" . rand(1000, 9999);
?>

<!DOCTYPE html>
<html lang="tr" data-theme="light">
<?php include 'inc/header.php'; ?>
<body>
    <?php include 'inc/sidebar.php'; ?>
    <main class="dashboard-main">
        <?php include 'inc/navbar.php'; ?>
        
        <div class="dashboard-main-body">
            <div class="d-flex flex-wrap align-items-center justify-content-between gap-3 mb-24">
                <h6 class="fw-semibold mb-0">Akıllı Fatura Sistemi</h6>
                <ul class="d-flex align-items-center gap-2">
                    <li class="fw-medium"><a href="invoice-list.php" class="hover-text-primary">Faturalar</a></li>
                    <li>-</li>
                    <li class="fw-medium">Yeni Ekle</li>
                </ul>
            </div>

            <?php if($mesaj != ""): ?>
                <div class="alert alert-<?php echo $mesaj_tur; ?> d-flex align-items-center gap-3 border-0 radius-12 px-32 py-16 mb-24 shadow-sm">
                    <?php if($mesaj_tur == 'success'): ?>
                        <div class="w-40-px h-40-px bg-success-main rounded-circle d-flex justify-content-center align-items-center flex-shrink-0">
                            <iconify-icon icon="lucide:check" class="text-white text-xl"></iconify-icon>
                        </div>
                    <?php else: ?>
                        <div class="w-40-px h-40-px bg-danger-main rounded-circle d-flex justify-content-center align-items-center flex-shrink-0">
                            <iconify-icon icon="lucide:alert-triangle" class="text-white text-xl"></iconify-icon>
                        </div>
                    <?php endif; ?>
                    <div>
                        <h6 class="text-md fw-semibold mb-0"><?php echo ($mesaj_tur == 'success') ? 'Başarılı!' : 'Hata'; ?></h6>
                        <p class="text-sm mb-0 text-secondary-light"><?php echo $mesaj; ?></p>
                    </div>
                </div>
            <?php endif; ?>

            <form action="" method="POST">
                <div class="row gy-4">
                    
                    <div class="col-lg-8">
                        <div class="card h-100 p-0 radius-12">
                            <div class="card-header border-bottom bg-base py-16 px-24 bg-primary-focus">
                                <h6 class="text-lg fw-semibold mb-0 text-primary-main">Müşteri Seçimi / Ekleme</h6>
                            </div>
                            <div class="card-body p-24">
                                <div class="row">
                                    <div class="col-md-6 mb-20">
                                        <label class="form-label fw-semibold text-primary-light text-sm mb-8">Müşteri Adı Soyadı <span class="text-danger">*</span></label>
                                        
                                        <input type="text" id="customer_name" name="customer_name" class="form-control radius-8" list="customer_list" placeholder="İsim yazmaya başlayın..." required autocomplete="off">
                                        <datalist id="customer_list">
                                            <?php foreach($all_customers as $c): ?>
                                                <option value="<?php echo htmlspecialchars($c['name']); ?>">
                                            <?php endforeach; ?>
                                        </datalist>
                                        <small class="text-success-main" id="customer_status"></small>
                                    </div>
                                    
                                    <div class="col-md-6 mb-20">
                                        <label class="form-label fw-semibold text-primary-light text-sm mb-8">Firma Adı</label>
                                        <input type="text" id="company_name" name="company_name" class="form-control radius-8">
                                    </div>

                                    <div class="col-md-4 mb-20">
                                        <label class="form-label fw-semibold text-primary-light text-sm mb-8">E-Posta</label>
                                        <input type="email" id="customer_email" name="customer_email" class="form-control radius-8">
                                    </div>
                                    <div class="col-md-4 mb-20">
                                        <label class="form-label fw-semibold text-primary-light text-sm mb-8">Cep Telefonu</label>
                                        <input type="text" id="customer_phone" name="customer_phone" class="form-control radius-8">
                                    </div>
                                    <div class="col-md-4 mb-20">
                                        <label class="form-label fw-semibold text-primary-light text-sm mb-8">Sabit Hat</label>
                                        <input type="text" id="customer_landline" name="customer_landline" class="form-control radius-8">
                                    </div>

                                    <div class="col-md-12">
                                        <label class="form-label fw-semibold text-primary-light text-sm mb-8">Adres</label>
                                        <textarea id="customer_address" name="customer_address" class="form-control radius-8" rows="2"></textarea>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="col-lg-4">
                        <div class="card h-100 p-0 radius-12">
                            <div class="card-header border-bottom bg-base py-16 px-24">
                                <h6 class="text-lg fw-semibold mb-0">Fatura Detayları</h6>
                            </div>
                            <div class="card-body p-24">
                                <div class="mb-20">
                                    <label class="form-label fw-semibold text-primary-light text-sm mb-8">Fatura No</label>
                                    <input type="text" name="invoice_no" class="form-control radius-8" value="<?php echo $rand_no; ?>">
                                </div>
                                <div class="mb-20">
                                    <label class="form-label fw-semibold text-primary-light text-sm mb-8">Fatura Tarihi</label>
                                    <input type="date" name="issue_date" class="form-control radius-8" value="<?php echo date('Y-m-d'); ?>">
                                </div>
                                <div class="mb-20">
                                    <label class="form-label fw-semibold text-primary-light text-sm mb-8">Son Ödeme Tarihi</label>
                                    <input type="date" name="due_date" class="form-control radius-8" value="<?php echo date('Y-m-d', strtotime('+7 days')); ?>">
                                </div>
                                <div class="mb-20">
                                    <label class="form-label fw-semibold text-primary-light text-sm mb-8">Durum</label>
                                    <select name="status" class="form-control radius-8">
                                        <option value="pending">Bekliyor</option>
                                        <option value="paid">Ödendi</option>
                                        <option value="unpaid">Ödenmedi</option>
                                        <option value="cancelled">İptal</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="col-lg-12">
                        <div class="card h-100 p-0 radius-12">
                            <div class="card-header border-bottom bg-base py-16 px-24 d-flex justify-content-between align-items-center">
                                <h6 class="text-lg fw-semibold mb-0">Hizmet / Ürün Kalemleri</h6>
                                <button type="button" id="addRowBtn" class="btn btn-primary text-sm btn-sm px-12 py-12 radius-8">+ Ekle</button>
                            </div>
                            <div class="card-body p-24">
                                <div class="table-responsive">
                                    <table class="table bordered-table sm-table mb-0" id="invoiceTable">
                                        <thead>
                                            <tr>
                                                <th width="40%">Açıklama</th>
                                                <th width="15%">Adet</th>
                                                <th width="20%">Birim Fiyat</th>
                                                <th width="20%">Toplam</th>
                                                <th width="5%">Sil</th>
                                            </tr>
                                        </thead>
                                        <tbody id="invoiceItems">
                                            <tr class="item-row">
                                                <td><input type="text" name="desc[]" class="form-control radius-8" placeholder="..." required></td>
                                                <td><input type="number" name="qty[]" class="form-control radius-8 qty" value="1" min="1"></td>
                                                <td><input type="number" name="price[]" class="form-control radius-8 price" value="0.00" step="0.01"></td>
                                                <td><input type="text" class="form-control radius-8 total" value="0.00" readonly></td>
                                                <td><button type="button" class="btn btn-danger-focus text-danger-main w-32-px h-32-px rounded-circle remove-row"><iconify-icon icon="mingcute:delete-2-line"></iconify-icon></button></td>
                                            </tr>
                                        </tbody>
                                        <tfoot>
                                            <tr>
                                                <td colspan="3" class="text-end fw-bold text-lg">GENEL TOPLAM:</td>
                                                <td colspan="2"><input type="text" id="grandTotal" class="form-control radius-8 fw-bold bg-light" value="0.00 ₺" readonly></td>
                                            </tr>
                                        </tfoot>
                                    </table>
                                </div>
                                <div class="d-flex justify-content-end mt-24">
                                    <button type="submit" class="btn btn-success px-32 py-12 radius-8">Faturayı Kaydet</button>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </form>
        </div>
        <?php include 'inc/copyright.php'; ?>
    </main>
    <?php include 'inc/footer.php'; ?>

    <script>
    $(document).ready(function() {
        
        // 1. CRM VERİSİ (PHP'den JS'e aktar)
        var customers = <?php echo $json_customers; ?>;

        // 2. MÜŞTERİ SEÇİMİ (Inputa yazıldıkça kontrol et)
        $("#customer_name").on('input', function() {
            var val = this.value;
            // Listeden eşleşen var mı bul
            var match = customers.find(c => c.name === val);

            if(match) {
                // Eşleşme Varsa: Bilgileri Doldur
                $("#company_name").val(match.company_name);
                $("#customer_email").val(match.email);
                $("#customer_phone").val(match.phone);
                $("#customer_landline").val(match.landline);
                $("#customer_address").val(match.address);
                $("#customer_status").text("✓ Kayıtlı müşteri bilgileri çekildi.");
            } else {
                // Eşleşme Yoksa: Yeni kayıt olacağı için temizlemiyoruz, kullanıcının yazdığı kalsın.
                $("#customer_status").text("");
            }
        });

        // 3. FİYAT HESAPLAMA SİSTEMİ (Standart)
        function calculateTotal() {
            let grandTotal = 0;
            $(".item-row").each(function() {
                let qty = parseFloat($(this).find(".qty").val()) || 0;
                let price = parseFloat($(this).find(".price").val()) || 0;
                let total = qty * price;
                $(this).find(".total").val(total.toFixed(2));
                grandTotal += total;
            });
            $("#grandTotal").val(grandTotal.toFixed(2) + " ₺");
        }
        $(document).on("input", ".qty, .price", function() { calculateTotal(); });
        $("#addRowBtn").click(function() {
            let html = `<tr class="item-row"><td><input type="text" name="desc[]" class="form-control radius-8" placeholder="..." required></td><td><input type="number" name="qty[]" class="form-control radius-8 qty" value="1" min="1"></td><td><input type="number" name="price[]" class="form-control radius-8 price" value="0.00" step="0.01"></td><td><input type="text" class="form-control radius-8 total" value="0.00" readonly></td><td><button type="button" class="btn btn-danger-focus text-danger-main w-32-px h-32-px rounded-circle remove-row"><iconify-icon icon="mingcute:delete-2-line"></iconify-icon></button></td></tr>`;
            $("#invoiceItems").append(html);
        });
        $(document).on("click", ".remove-row", function() {
            if($(".item-row").length > 1) { $(this).closest("tr").remove(); calculateTotal(); }
        });
    });
    </script>
</body>
</html>