<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

session_start();
include 'db.php';

if (!isset($_SESSION['username'])) {
    header("Location: index.php");
    exit;
}

// --- Ambil data master untuk dropdown ---
$pelanggan = $conn->query("SELECT no_id, Nama FROM pelanggan");
$kendaraan = $conn->query("SELECT no_id, Merk_kendaraan, Plat_nomer FROM kendaraan");
$onderdil  = $conn->query("SELECT no_id, Nama_onderdil, Harga_jual FROM onderdil");

// --- Jika form disubmit ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $no_plg        = $_POST['no_plg'];
    $no_kendaraan  = $_POST['no_kendaraan'];
    $no_onderdil   = $_POST['no_onderdil'];
    $jumlah        = (int)$_POST['jumlah'];
    $biaya_service = (int)$_POST['biaya_service'];
    $harga_lain    = (int)$_POST['harga_lain'];
    $jumlah_lain   = (int)$_POST['jumlah_lain'];
    $diskon_persen = (float)$_POST['diskon'];
    $lunas         = isset($_POST['lunas']) ? 1 : 0;

    // Ambil harga onderdil
    $stmt = $conn->prepare("SELECT Harga_jual FROM onderdil WHERE no_id=?");
    $stmt->bind_param("i", $no_onderdil);
    $stmt->execute();
    $stmt->bind_result($harga);
    $stmt->fetch();
    $stmt->close();

    // Hitung total
    $total_onderdil = $harga * $jumlah;
    $total_service  = $biaya_service;
    $total_lain     = $harga_lain * $jumlah_lain;
    $subtotal       = $total_onderdil + $total_service + $total_lain;

    $diskon_rp   = $subtotal * ($diskon_persen / 100);
    $total_biaya = $subtotal - $diskon_rp;

    // Simpan ke tabel transaksi (dengan Total_Biaya)
    $stmt = $conn->prepare("
        INSERT INTO transaksi (Tanggal_beli, No_plg, No_kendaraan, No_onderdil, Lunas, Total_Biaya)
        VALUES (NOW(), ?, ?, ?, ?, ?)
    ");
    $stmt->bind_param("iiiii", $no_plg, $no_kendaraan, $no_onderdil, $lunas, $total_biaya);
    $stmt->execute();
    $no_trans = $conn->insert_id;
    $stmt->close();

    // Simpan ke tabel service (opsional)
    if ($biaya_service > 0) {
        $stmt = $conn->prepare("
            INSERT INTO service (Tanggal_service, Biaya_service, Discount, Lunas)
            VALUES (CURDATE(), ?, ?, ?)
        ");
        $stmt->bind_param("iii", $biaya_service, $diskon_rp, $lunas);
        $stmt->execute();
        $stmt->close();
    }

    // Simpan ke tabel lain_lain (opsional)
    if ($harga_lain > 0) {
        $stmt = $conn->prepare("
            INSERT INTO lain_lain (Tanggal_service, Biaya_lain, Harga_satuan, Jumlah_beli, Lunas)
            VALUES (CURDATE(), 'Biaya Tambahan', ?, ?, ?)
        ");
        $stmt->bind_param("iii", $harga_lain, $jumlah_lain, $lunas);
        $stmt->execute();
        $stmt->close();
    }

    echo "<script>alert('Transaksi berhasil disimpan! Total Biaya Akhir: Rp".number_format($total_biaya,0,',','.')."');</script>";
}
?>

<html>
<head>
<title>Transaksi Bengkel</title>
<style>
body { font-family: Verdana; background: #f2f2f2; }
.container { width: 70%; margin: 30px auto; background: white; padding: 20px; border-radius: 12px; box-shadow: 0 0 10px #aaa; }
input, select { padding: 8px; width: 95%; margin-top: 4px; }
button { background: #0066cc; color: white; padding: 10px 20px; border: none; border-radius: 6px; cursor: pointer; }
button:hover { background: #004999; }
table { border-collapse: collapse; width: 100%; margin-top: 25px; }
th, td { border: 1px solid #ccc; padding: 8px; text-align: center; }
th { background: #007bff; color: white; }
</style>
</head>

<body>
<div class="container">
<center><h2>🧾 Transaksi Bengkel Surabaya Motor</h2></center>

<form method="post">
<label>Pelanggan:</label><br>
<select name="no_plg" required>
<option value="">-- Pilih Pelanggan --</option>
<?php while($p = $pelanggan->fetch_assoc()): ?>
<option value="<?= $p['no_id'] ?>"><?= htmlspecialchars($p['Nama']) ?></option>
<?php endwhile; ?>
</select><br><br>

<label>Kendaraan:</label><br>
<select name="no_kendaraan" required>
<option value="">-- Pilih Kendaraan --</option>
<?php while($k = $kendaraan->fetch_assoc()): ?>
<option value="<?= $k['no_id'] ?>"><?= htmlspecialchars($k['Merk_kendaraan']) ?> (<?= htmlspecialchars($k['Plat_nomer']) ?>)</option>
<?php endwhile; ?>
</select><br><br>

<label>Onderdil:</label><br>
<select name="no_onderdil" required>
<option value="">-- Pilih Onderdil --</option>
<?php while($o = $onderdil->fetch_assoc()): ?>
<option value="<?= $o['no_id'] ?>"><?= htmlspecialchars($o['Nama_onderdil']) ?> - Rp<?= number_format($o['Harga_jual'],0,',','.') ?></option>
<?php endwhile; ?>
</select><br><br>

<label>Jumlah Onderdil:</label><br>
<input type="number" name="jumlah" min="1" value="1" required><br><br>

<label>Biaya Service (Rp):</label><br>
<input type="number" name="biaya_service" min="0" value="0"><br><br>

<label>Biaya Lain-lain (Rp):</label><br>
<input type="number" name="harga_lain" min="0" value="0"><br><br>

<label>Jumlah Lain-lain:</label><br>
<input type="number" name="jumlah_lain" min="1" value="1"><br><br>

<label>Diskon (%):</label><br>
<input type="number" name="diskon" min="0" max="100" value="0"><br><br>

<label>Status Pembayaran:</label><br>
<input type="checkbox" name="lunas" value="1"> Sudah Lunas<br><br>

<center><button type="submit">💾 Simpan Transaksi</button></center>
</form>

<hr>

<h3>📋 Riwayat Transaksi</h3>
<table>
<tr>
<th>Tanggal</th>
<th>Pelanggan</th>
<th>Kendaraan</th>
<th>Onderdil</th>
<th>Total Biaya (Rp)</th>
<th>Status</th>
<th>Aksi</th>
</tr>

<?php
$result = $conn->query("
    SELECT 
        t.no_trans,
        t.Tanggal_beli, 
        p.Nama AS pelanggan, 
        k.Plat_nomer AS plat, 
        o.Nama_onderdil AS onderdil,
        t.Total_Biaya, 
        t.Lunas
    FROM transaksi t
    JOIN pelanggan p ON t.No_plg = p.no_id
    JOIN kendaraan k ON t.No_kendaraan = k.no_id
    JOIN onderdil o ON t.No_onderdil = o.no_id
    ORDER BY t.no_trans DESC
");

while ($row = $result->fetch_assoc()) {
    $status = $row['Lunas'] ? '✅ Lunas' : '❌ Belum Lunas';
?>
<tr>
  <td><?= $row['Tanggal_beli'] ?></td>
  <td><?= $row['pelanggan'] ?></td>
  <td><?= $row['plat'] ?></td>
  <td><?= $row['onderdil'] ?></td>
  <td align="right">Rp<?= number_format($row['Total_Biaya'],0,',','.') ?></td>
  <td><?= $status ?></td>
  <td><a href="cetak_invoice.php?no_trans=<?= $row['no_trans'] ?>" target="_blank">🖨️ Cetak Nota</a></td>
</tr>
<?php } $conn->close(); ?>
</table>
</div>
</body>
</html>
