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

session_start();
require "../config.php";

/* ================= LOGIN ================= */

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

if($_SESSION['role'] != 'admin3'){
    header("Location: /login.php");
    exit;
}

/* ================= TOTAL ================= */

$total = $conn->query("
SELECT COUNT(*) as jml FROM rekomtek
")->fetch_assoc()['jml'];

$menunggu = $conn->query("
SELECT COUNT(*) as jml 
FROM rekomtek
WHERE status='Menunggu'
")->fetch_assoc()['jml'];

$diterima = $conn->query("
SELECT COUNT(*) as jml 
FROM rekomtek
WHERE status='Diterima'
")->fetch_assoc()['jml'];

$ditolak = $conn->query("
SELECT COUNT(*) as jml 
FROM rekomtek
WHERE status='Ditolak'
")->fetch_assoc()['jml'];

$selesai = $conn->query("
SELECT COUNT(*) as jml 
FROM rekomtek
WHERE status='Selesai'
")->fetch_assoc()['jml'];

/* ================= TAMBAH DATA ================= */

if(isset($_POST['simpan'])){

    $nomor_sk = $conn->real_escape_string($_POST['nomor_sk']);
    $sumber_air = $conn->real_escape_string($_POST['sumber_air']);
    $nama_perusahaan = $conn->real_escape_string($_POST['nama_perusahaan']);
    $masa_berlaku = $conn->real_escape_string($_POST['masa_berlaku']);

    $conn->query("
    INSERT INTO master_sk
    (nomor_sk, sumber_air, nama_perusahaan, masa_berlaku)
    VALUES
    ('$nomor_sk','$sumber_air','$nama_perusahaan','$masa_berlaku')
    ");

    header("Location: master_sk.php");
    exit;
}

/* ================= UPDATE DATA ================= */

if(isset($_POST['update'])){

    $id = (int)$_POST['id'];

    $nomor_sk = $conn->real_escape_string($_POST['nomor_sk']);
    $sumber_air = $conn->real_escape_string($_POST['sumber_air']);
    $nama_perusahaan = $conn->real_escape_string($_POST['nama_perusahaan']);
    $masa_berlaku = $conn->real_escape_string($_POST['masa_berlaku']);

    $conn->query("
    UPDATE master_sk
    SET
    nomor_sk='$nomor_sk',
    sumber_air='$sumber_air',
    nama_perusahaan='$nama_perusahaan',
    masa_berlaku='$masa_berlaku'
    WHERE id='$id'
    ");

    header("Location: master_sk.php");
    exit;
}

/* ================= HAPUS DATA ================= */

if(isset($_GET['hapus'])){

    $id = (int)$_GET['hapus'];

    $conn->query("
    DELETE FROM master_sk
    WHERE id='$id'
    ");

    header("Location: master_sk.php");
    exit;
}

/* ================= PAGINATION ================= */

$limit = 10;

$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;

if($page < 1){
    $page = 1;
}

$offset = ($page - 1) * $limit;

/* ================= TOTAL DATA ================= */

$totalData = $conn->query("
SELECT COUNT(*) as total
FROM master_sk
")->fetch_assoc()['total'];

$totalPage = ceil($totalData / $limit);

/* ================= DATA ================= */

$data = $conn->query("
SELECT *
FROM master_sk
ORDER BY id DESC
LIMIT $limit OFFSET $offset
");

if(isset($_POST['import_csv'])){

    $file = $_FILES['file_csv']['tmp_name'];

    if(($handle = fopen($file, "r")) !== FALSE){

        fgetcsv($handle);

        while(($row = fgetcsv($handle, 1000, ",")) !== FALSE){

            $nomor_sk = $conn->real_escape_string($row[0]);
            $sumber_air = $conn->real_escape_string($row[1]);
            $nama_perusahaan = $conn->real_escape_string($row[2]);
            $masa_berlaku = $conn->real_escape_string($row[3]);

            $cek = $conn->query("
            SELECT id
            FROM master_sk
            WHERE nomor_sk='$nomor_sk'
            ");

            if($cek->num_rows > 0){

                $conn->query("
                UPDATE master_sk
                SET
                    sumber_air='$sumber_air',
                    nama_perusahaan='$nama_perusahaan',
                    masa_berlaku='$masa_berlaku'
                WHERE nomor_sk='$nomor_sk'
                ");

            }else{

                $conn->query("
                INSERT INTO master_sk
                (
                    nomor_sk,
                    sumber_air,
                    nama_perusahaan,
                    masa_berlaku
                )
                VALUES
                (
                    '$nomor_sk',
                    '$sumber_air',
                    '$nama_perusahaan',
                    '$masa_berlaku'
                )
                ");

            }

        }

        fclose($handle);

    }

    header("Location: master_sk.php");
    exit;
}
?>

<!DOCTYPE html>
<html lang="id">
<head>

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">

<title>Master SK</title>

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">

<link rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">

<style>

body{
    background:#f4f6f9;
    font-family:'Segoe UI',sans-serif;
}

.sidebar{
    width:250px;
    height:100vh;
    position:fixed;
    left:0;
    top:0;
    background:#003b7a;
    padding-top:20px;
}

.sidebar h4{
    color:white;
    text-align:center;
    margin-bottom:30px;
    font-weight:bold;
}

.sidebar a{
    display:block;
    color:white;
    padding:14px 20px;
    text-decoration:none;
}

.sidebar a:hover{
    background:rgba(255,255,255,0.15);
}

.sidebar .badge{
    float:right;
}

.main{
    margin-left:250px;
    padding:30px;
}

.card{
    border-radius:15px;
}

.table td,
.table th{
    vertical-align:middle;
}

</style>

</head>

<body>

<!-- SIDEBAR -->

<div class="sidebar">

<h4>📁 Admin Laporan Triwulan</h4>


<a href="laporan_masuk">
<i class="fa fa-file-alt"></i>
Laporan Masuk
<span class="badge bg-warning text-dark">
<?= $menunggu ?>
</span>
</a>

<a href="laporan_ditolak">
<i class="fa fa-times-circle"></i>
Laporan Ditolak
<span class="badge bg-danger">
<?= $ditolak ?>
</span>
</a>

<a href="laporan_diterima">
<i class="fa fa-check-circle"></i>
Laporan Diterima
<span class="badge bg-success">
<?= $diterima ?>
</span>
</a>

<a href="rekap_triwulan">
    <i class="fa fa-clipboard-list"></i>
    Laporan Triwulan
</a>

<a href="masa_berlaku_sk">
    <i class="fa fa-calendar-times"></i>
    SK Perlu Perpanjangan
</a>

<a href="master_sk">
<i class="fa fa-database"></i>
Master SK
</a>

<a href="/login">
<i class="fa fa-sign-out-alt"></i>
Logout
</a>

</div>

<!-- MAIN -->

<div class="main">

<h3 class="mb-4 fw-bold">
🗂 Master SK
</h3>

<!-- FORM -->

<div class="card shadow border-0 mb-4">

<div class="card-body">

<form method="POST">

<div class="row">

    <div class="col-md-6 mb-3">
        <label class="form-label">Nomor SK</label>
        <input type="text"
               name="nomor_sk"
               class="form-control"
               required>
    </div>
    
    <div class="col-md-6 mb-3">
        <label class="form-label">Masa Berlaku SK</label>
        <input type="date"
               name="masa_berlaku"
               value="<?= $d['masa_berlaku'] ?>"
               class="form-control"
               required>
    </div>

    <div class="col-md-6 mb-3">
        <label class="form-label">Sumber Air</label>
        <input type="text"
               name="sumber_air"
               class="form-control"
               required>
    </div>

    <div class="col-md-6 mb-3">
        <label class="form-label">Nama Perusahaan</label>
        <input type="text"
               name="nama_perusahaan"
               class="form-control"
               required>
    </div>

</div>

<div class="text-center mt-3">

    <button type="submit"
            name="simpan"
            class="btn btn-primary px-4">

        <i class="fa fa-save"></i>
        Simpan

    </button>

</div>

</form>

</div>

</div>

<!-- SEARCH -->

<form method="GET" class="mb-3">

<div class="row">

<div class="col-md-4">

<input type="text"
name="search"
class="form-control"
placeholder="Cari nomor SK / perusahaan..."
value="<?= $_GET['search'] ?? '' ?>">

</div>

<div class="col-md-2">

<button class="btn btn-primary w-100">

<i class="fa fa-search"></i>
Cari

</button>

</div>

<div class="col-md-2">

<a href="template_sk.csv"
class="btn btn-info w-100">

<i class="fa fa-download"></i>
Template

</a>

</div>

<div class="col-md-2">

<button
type="button"
class="btn btn-warning w-100"
data-bs-toggle="modal"
data-bs-target="#importCSV">

<i class="fa fa-file-csv"></i>
Import CSV

</button>

</div>

<div class="col-md-2">

<a href="export_master_sk"
class="btn btn-success w-100">

<i class="fa fa-file-excel"></i>
Export Excel

</a>

</div>

</div>

</form>

<!-- TABEL -->

<div class="card shadow border-0">

<div class="card-body">

<div class="table-responsive">

<table class="table table-bordered table-striped">

<thead class="table-dark text-center">

<tr>

<th width="60">No</th>
<th>Nomor SK</th>
<th>Sumber Air</th>
<th>Nama Perusahaan</th>
<th>Masa Berlaku SK</th>
<th width="180">Aksi</th>

</tr>

</thead>

<tbody>

<?php
$no = $offset + 1;

while($d = $data->fetch_assoc()):
?>

<tr>

<td class="text-center">
<?= $no++ ?>
</td>

<td>
<?= $d['nomor_sk'] ?>
</td>

<td>
<?= $d['sumber_air'] ?>
</td>

<td>
<?= $d['nama_perusahaan'] ?>
</td>

<td>
<?= date('d-m-Y', strtotime($d['masa_berlaku'])) ?>
</td>

<td class="text-center">

<!-- BUTTON EDIT -->

<button
class="btn btn-warning btn-sm"
data-bs-toggle="modal"
data-bs-target="#edit<?= $d['id'] ?>">

Edit

</button>

<!-- BUTTON HAPUS -->

<a href="master_sk?hapus=<?= $d['id'] ?>"
class="btn btn-danger btn-sm"
onclick="return confirm('Hapus data ini?')">

Hapus

</a>

</td>

</tr>

<!-- MODAL EDIT -->

<div class="modal fade"
id="edit<?= $d['id'] ?>"
tabindex="-1">

<div class="modal-dialog">

<div class="modal-content">

<form method="POST">

<div class="modal-header bg-warning">

<h5 class="modal-title">
Edit Data
</h5>

<button type="button"
class="btn-close"
data-bs-dismiss="modal"></button>

</div>

<div class="modal-body">

<input type="hidden"
name="id"
value="<?= $d['id'] ?>">

<div class="mb-3">

<label class="form-label">
Nomor SK
</label>

<input type="text"
name="nomor_sk"
class="form-control"
value="<?= $d['nomor_sk'] ?>"
required>

</div>

<div class="mb-3">

<label class="form-label">
Sumber Air
</label>

<input type="text"
name="sumber_air"
class="form-control"
value="<?= $d['sumber_air'] ?>"
required>

</div>

<div class="mb-3">

<label class="form-label">
Nama Perusahaan
</label>

<input type="text"
name="nama_perusahaan"
class="form-control"
value="<?= $d['nama_perusahaan'] ?>"
required>

</div>

<div class="col-md-4 mb-3">

<label class="form-label">
Masa Berlaku SK
</label>

<input type="date"
name="masa_berlaku"
class="form-control"
required>

</div>
</div>

<div class="modal-footer">

<button type="button"
class="btn btn-secondary"
data-bs-dismiss="modal">

Batal

</button>

<button type="submit"
name="update"
class="btn btn-warning">

Update

</button>

</div>

</form>

</div>

</div>

</div>

<?php endwhile; ?>

</tbody>

</table>

<!-- PAGINATION -->

<div class="mt-3 text-center">

<?php if($page > 1){ ?>

<a href="?page=<?= $page-1 ?>"
class="btn btn-sm btn-secondary">

Sebelumnya

</a>

<?php } ?>

<?php

$start = max(1, $page - 1);
$end = min($totalPage, $page + 1);

for($i = $start; $i <= $end; $i++):

?>

<a href="?page=<?= $i ?>"
class="btn btn-sm <?= ($i == $page) ? 'btn-primary' : 'btn-light border' ?>">

<?= $i ?>

</a>

<?php endfor; ?>

<?php if($page < $totalPage){ ?>

<a href="?page=<?= $page+1 ?>"
class="btn btn-sm btn-secondary">

Selanjutnya

</a>

<?php } ?>

</div>

</div>

</div>

</div>

<div class="modal fade" id="importCSV">

<div class="modal-dialog">

<div class="modal-content">

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

<div class="modal-header bg-warning text-black">

<h5 class="modal-title">
Import CSV
</h5>

<button
type="button"
class="btn-close"
data-bs-dismiss="modal"></button>

</div>

<div class="modal-body">

<input
type="file"
name="file_csv"
accept=".csv"
class="form-control"
required>

</div>

<div class="modal-footer">

<button
type="submit"
name="import_csv"
class="btn btn-warning">

Import

</button>

</div>

</form>

</div>

</div>

</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>

</body>
</html>