<?php
require_once __DIR__ . '/vendor/autoload.php';

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Fill;

if (isset($_GET['export']) && $_GET['export'] === 'excel') {
    $conn = new mysqli('localhost', 'root', '', 'klinik');
    if ($conn->connect_error) {
        die('Koneksi gagal: ' . $conn->connect_error);
    }

    $spreadsheet = new Spreadsheet();
    $sheet = $spreadsheet->getActiveSheet();

    $sheet->mergeCells('A1:G1');
    $sheet->setCellValue('A1', 'KLINIK PT. SINDO LUMBER');
    $sheet->getStyle('A1')->getFont()->setBold(true)->setSize(14);
    $sheet->getStyle('A1')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);

    $sheet->mergeCells('A2:G2');
    $sheet->setCellValue('A2', 'LAPORAN OBAT MASUK');
    $sheet->getStyle('A2')->getFont()->setBold(true)->setSize(12);
    $sheet->getStyle('A2')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);

    $sheet->mergeCells('A3:G3');
    $sheet->setCellValue('A3', 'Tanggal Cetak: ' . date('d-m-Y'));
    $sheet->getStyle('A3')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_RIGHT);

    $sheet->setCellValue('A5', 'No');
    $sheet->setCellValue('B5', 'Nama Obat');
    $sheet->setCellValue('C5', 'Satuan');
    $sheet->setCellValue('D5', 'Jumlah');
    $sheet->setCellValue('E5', 'Tanggal Masuk');
    $sheet->setCellValue('F5', 'Keterangan');
    $sheet->setCellValue('G5', 'Status');

    $headerStyle = [
        'font' => ['bold' => true],
        'alignment' => ['horizontal' => Alignment::HORIZONTAL_CENTER],
        'borders' => ['allBorders' => ['borderStyle' => Border::BORDER_THIN]],
        'fill' => [
            'fillType' => Fill::FILL_SOLID,
            'startColor' => ['rgb' => 'D9D9D9']
        ],
    ];
    $sheet->getStyle('A5:G5')->applyFromArray($headerStyle);

    $sql = "SELECT * FROM obat_masuk ORDER BY tanggal DESC";
    $result = $conn->query($sql);
    $row = 6;
    $no = 1;

    while ($data = $result->fetch_assoc()) {
        $sheet->setCellValue('A' . $row, $no++);
        $sheet->setCellValue('B' . $row, $data['nama']);
        $sheet->setCellValue('C' . $row, $data['satuan']);
        $sheet->setCellValue('D' . $row, $data['jumlah']);
        $sheet->setCellValue('E' . $row, date('d-m-Y', strtotime($data['tanggal'])));
        $sheet->setCellValue('F' . $row, $data['keterangan']);
        $sheet->setCellValue('G' . $row, $data['expired']);

        $sheet->getStyle("A$row:G$row")->getBorders()->getAllBorders()->setBorderStyle(Border::BORDER_THIN);
        $row++;
    }

    $row += 2;
    $sheet->mergeCells("F$row:G$row");
    $sheet->setCellValue("F$row", "Disetujui oleh,\nKepala Klinik");
    $sheet->getStyle("F$row")->getAlignment()->setWrapText(true)->setHorizontal(Alignment::HORIZONTAL_CENTER);

    $row += 4;
    $sheet->mergeCells("F$row:G$row");
    $sheet->setCellValue("F$row", "(____________________)");
    $sheet->getStyle("F$row")->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);

    foreach (range('A', 'G') as $col) {
        $sheet->getColumnDimension($col)->setAutoSize(true);
    }

    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Disposition: attachment;filename="Laporan_Obat_Masuk.xlsx"');
    header('Cache-Control: max-age=0');

    $writer = new Xlsx($spreadsheet);
    $writer->save('php://output');
    exit;
}
?>

<?php
session_start();
@date_default_timezone_set('Asia/Pontianak');

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

$conn = new mysqli('localhost', 'root', '', 'klinik');
if ($conn->connect_error) { die('Koneksi gagal: ' . $conn->connect_error); }

$JENIS_LAPORAN = 'obat_masuk';

function formatTanggalIndo($tanggal) {
    if (!$tanggal || $tanggal === '0000-00-00') return 'Ngurit Base Camp, -';
    $bulan = ['Januari','Februari','Maret','April','Mei','Juni','Juli','Agustus','September','Oktober','November','Desember'];
    $ts = strtotime($tanggal);
    if ($ts === false) return 'Ngurit Base Camp, -';
    $tgl = date('d', $ts);
    $bln = $bulan[(int)date('n', $ts) - 1];
    $thn = date('Y', $ts);
    return "Ngurit Base Camp, $tgl $bln $thn";
}

function parseTanggalFlexible($text) {
    $text = strip_tags($text);
    $text = trim($text);
    $text = preg_replace('/^Ngurit Base Camp,\s*/iu', '', $text);
    $bulanMap = [
        'januari'=>1,'februari'=>2,'maret'=>3,'april'=>4,
        'mei'=>5,'juni'=>6,'juli'=>7,'agustus'=>8,
        'september'=>9,'oktober'=>10,'november'=>11,'desember'=>12
    ];
    if (preg_match('/(\d{1,2})\s+([A-Za-z]+)\s+(\d{4})/u', $text, $m)) {
        $d=(int)$m[1]; $b=strtolower($m[2]); $y=(int)$m[3];
        if (isset($bulanMap[$b])) return sprintf('%04d-%02d-%02d',$y,$bulanMap[$b],$d);
    }
    $alt = str_replace('/', '-', $text);
    $ts = strtotime($alt);
    return $ts!==false ? date('Y-m-d',$ts) : date('Y-m-d');
}

function hitungStatusExpired($tanggalKadaluarsa, $jumlah) {
    $today = date('Y-m-d');
    if ($tanggalKadaluarsa && strtotime($tanggalKadaluarsa) < strtotime($today)) {
        return 'Expired';
    } elseif ((int)$jumlah === 0) {
        return 'Habis';
    }
    return 'Ada';
}

if(isset($_POST['obat_submit'])){
    $id_edit = intval($_POST['id_edit'] ?? 0);
    $nama=trim($_POST['nama']??'');
    $supplier=trim($_POST['supplier']??'');
    $satuan=trim($_POST['satuan']??'');
    $jumlah=(int)($_POST['jumlah']??0);
    $tanggal_masuk=$_POST['tanggal_masuk']??date('Y-m-d'); 
    $tanggal=$_POST['tanggal']??date('Y-m-d');             
    $keterangan=trim($_POST['keterangan']??'');           
    $statusExpired=hitungStatusExpired($tanggal,$jumlah);
    if($id_edit>0){
        $stmt=$conn->prepare('UPDATE obat_masuk SET nama=?, supplier=?, satuan=?, jumlah=?, tanggal_masuk=?, tanggal=?, expired=?, keterangan=? WHERE id=?');
        $stmt->bind_param('sssissssi', $nama, $supplier, $satuan, $jumlah, $tanggal_masuk, $tanggal, $statusExpired, $keterangan, $id_edit);
        $stmt->execute();
    } else {
        $stmt=$conn->prepare('INSERT INTO obat_masuk (nama, supplier, satuan, jumlah, tanggal_masuk, tanggal, expired, keterangan) VALUES (?, ?, ?, ?, ?, ?, ?, ?)');
        $stmt->bind_param('sssissss', $nama, $supplier, $satuan, $jumlah, $tanggal_masuk, $tanggal, $statusExpired, $keterangan);
        $stmt->execute();
    }
    header('Location: obat-masuk.php');
    exit;
}

if(isset($_GET['hapus'])){
    $id=(int)$_GET['hapus'];
    $stmt=$conn->prepare('DELETE FROM obat_masuk WHERE id=?');
    $stmt->bind_param('i',$id);
    $stmt->execute();
    header('Location: obat-masuk.php');
    exit;
}

$data=$conn->query('SELECT * FROM obat_masuk ORDER BY id ASC');
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <title>Obat Masuk</title>
    <style>
        body { 
            font-family: 'Times New Roman'; padding: 30px;
        }
        .kop-header { 
            display: flex; 
            justify-content: space-between; 
            align-items: center; 
        }
        .kop-teks { 
            flex: 1; 
            text-align: center; 
        }
        .kop-teks h2, .kop-teks h3, .kop-teks h4 {
            margin: 3px 0;
            cursor: pointer;
        }
        .logo { 
            width: 80px;
        }
        .garis-bawah { 
            border-bottom: 2px solid black;
            margin-top: 10px; 
        }
        .btn-container {
            display: flex; 
            justify-content: center; 
            gap: 20px; 
            margin: 20px 0; 
            flex-wrap: wrap; 
        }
        .print-btn, .back-btn, .excel-btn { 
            padding: 10px 20px;
            color: white;
            border-radius: 6px;
            text-decoration: none; 
        }
        .print-btn {
            background: #0d47a1; 
        }
        .back-btn { 
            background: #8e44ad;
        }
        .excel-btn { 
            background: #2e7d32;
        }
        .print-btn:hover {
            background: #08306b; 
        }
        .back-btn:hover { 
            background: #6c3483; 
        }
        .excel-btn:hover { 
            background: #1b5e20;
        }
        .form-input {
            max-width: 700px; 
            margin: 30px auto; 
            background: #f9f9f9; 
            padding: 20px; 
            border-radius: 8px; 
        }
        .form-input input, .form-input select {
            width: 100%; 
            padding: 10px;
            margin: 8px 0; 
            border: 1px solid #ccc; 
            border-radius: 6px; 
        }
        .form-input button {
            background: #4CAF50;
            color: #fff; 
            border: none;
            padding: 10px 20px; 
            border-radius: 6px; 
            cursor: pointer;
        }
        .form-input button:hover {
            background: #388e3c; 
        }
        table { 
            width: 100%; 
            border-collapse: collapse;
            margin-top: 30px; 
        }
        th, td { 
            border: 1px solid #000; 
            padding: 8px; 
            text-align: center; 
        }
        th { 
            background: #388e3c; 
            color: white; 
        }
        .action a { 
            background: #d32f2f; 
            padding: 4px 10px; 
            color: white; 
            text-decoration: none; 
            border-radius: 4px; 
        }
        .action a.edit-btn { 
            background: #f39c12; 
            margin-right: 4px; 
        }
    </style>
</head>
<body>

<div class="btn-container">
    <a href="#" class="print-btn" onclick="window.print()">🖨️Cetak </a>
    <a href="obat-masuk.php?export=excel" class="excel-btn">📥 Expor </a>
    <a href="home.php" class="back-btn">🏠 Kembali</a>
</div>

<div class="form-input">
    <form method="POST">
        <input type="hidden" name="id_edit" id="id_edit" value="">
        
        <select name="nama" id="nama" required class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-indigo-500">
            <option value="">Pilih Obat</option>
            <?php
            $obatResult = $conn->query("SELECT * FROM data_obat");
            while ($obat = $obatResult->fetch_assoc()) {
                echo '<option value="' . htmlspecialchars($obat['nama_obat']) . '">' . htmlspecialchars($obat['nama_obat']) . '</option>';
            }
            ?>
        </select>

        <input type="text" name="supplier" placeholder="Supplier" required>
        <input type="text" name="satuan" placeholder="Satuan" required>
        <input type="number" name="jumlah" placeholder="Jumlah" required>
        <input type="date" name="tanggal_masuk" required value="<?php echo date('Y-m-d'); ?>">
        <input type="date" name="tanggal" required value="<?php echo date('Y-m-d'); ?>">
        <input type="text" name="keterangan" placeholder="Keadaan" required>
        <button type="submit" name="obat_submit"> + Tambah Obat</button>
    </form>
</div>

<table>
    <thead>
        <tr>
            <th>No</th>
            <th>Nama</th>
            <th>Supplier</th>
            <th>Satuan</th>
            <th>Jumlah</th>
            <th>Tanggal Masuk</th>
            <th>Kadaluarsa</th>
            <th>Keadaan</th>
            <th>Keterangan</th>
            <th class="action">Aksi</th>
        </tr>
    </thead>
    <tbody>
    <?php if ($data && $data->num_rows > 0): $no = 1; while ($row = $data->fetch_assoc()): ?>
        <tr data-row-id="<?php echo $row['id']; ?>">
            <td><?php echo $no++; ?></td>
            <td><?php echo htmlspecialchars($row['nama']); ?></td>
            <td><?php echo htmlspecialchars($row['supplier']); ?></td>
            <td><?php echo htmlspecialchars($row['satuan']); ?></td>
            <td><?php echo htmlspecialchars($row['jumlah']); ?></td>
            <td><?php echo htmlspecialchars($row['tanggal_masuk']); ?></td>
            <td><?php echo htmlspecialchars($row['tanggal']); ?></td>
            <td><?php echo htmlspecialchars($row['keterangan']); ?></td>
            <td><?php echo htmlspecialchars($row['expired']); ?></td>
            <td class="action">
                <a href="#" class="edit-btn" 
                   data-id="<?php echo $row['id']; ?>" 
                   data-nama="<?php echo htmlspecialchars($row['nama'], ENT_QUOTES); ?>"
                   data-supplier="<?php echo htmlspecialchars($row['supplier'], ENT_QUOTES); ?>"
                   data-satuan="<?php echo htmlspecialchars($row['satuan'], ENT_QUOTES); ?>"
                   data-jumlah="<?php echo htmlspecialchars($row['jumlah'], ENT_QUOTES); ?>"
                   data-tanggal-masuk="<?php echo htmlspecialchars($row['tanggal_masuk'], ENT_QUOTES); ?>"
                   data-tanggal="<?php echo htmlspecialchars($row['tanggal'], ENT_QUOTES); ?>">Edit</a>
                <a href="?hapus=<?php echo $row['id']; ?>" onclick="return confirm('Yakin hapus data ini?');">Hapus</a>
            </td>
        </tr>
    <?php endwhile; else: ?>
        <tr><td colspan="10">Belum ada data.</td></tr>
    <?php endif; ?>
    </tbody>
</table>

<script>
function fillFormForEdit(id, nama, supplier, satuan, jumlah, tanggal_masuk, tanggal, keterangan) {
    document.getElementById('id_edit').value = id;
    document.querySelector('select[name="nama"]').value = nama;
    document.querySelector('input[name="supplier"]').value = supplier;
    document.querySelector('input[name="satuan"]').value = satuan;
    document.querySelector('input[name="jumlah"]').value = jumlah;
    document.querySelector('input[name="tanggal_masuk"]').value = tanggal_masuk;
    document.querySelector('input[name="tanggal"]').value = tanggal;
    document.querySelector('input[name="keterangan"]').value = keterangan;
}

// Event listener for edit buttons
document.querySelectorAll('.edit-btn').forEach(button => {
    button.addEventListener('click', function(event) {
        event.preventDefault();
        const id = this.dataset.id;
        const nama = this.dataset.nama;
        const supplier = this.dataset.supplier;
        const satuan = this.dataset.satuan;
        const jumlah = this.dataset.jumlah;
        const tanggal_masuk = this.dataset.tanggalMasuk;
        const tanggal = this.dataset.tanggal;
        const keterangan = this.dataset.keterangan;

        fillFormForEdit(id, nama, supplier, satuan, jumlah, tanggal_masuk, tanggal, keterangan);
    });
});
</script>

</body>
</html>
