<?php
// Koneksi ke database
define('DB_HOST', 'localhost');
define('DB_USER', 'wiselie_nanda');
define('DB_PASS', 'Clemira123');
define('DB_NAME', 'wiselie_inventory');

// Membuat koneksi
$connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);

// Periksa koneksi
if ($connection->connect_error) {
    die("Koneksi ke database gagal: " . $connection->connect_error);
}

// Inisialisasi pesan notifikasi
$msg = "";

// Fungsi untuk membuat kode otomatis
function generateCode($connection)
{
    $query = "SELECT MAX(id) AS max_id FROM indirect_code";
    $result = $connection->query($query);
    $maxId = 0;

    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        $maxId = $row['max_id'];
    }

    $newId = $maxId + 1;
    return 'IND-' . str_pad($newId, 5, '0', STR_PAD_LEFT); // Format: IND-00001
}

// Proses untuk input manual
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['form_type']) && $_POST['form_type'] === 'normal_form') {
    $name = $connection->real_escape_string($_POST['name']);
    $code = generateCode($connection);

    // Upload file
    $targetDir = "upload/indirect/";
    $fileName = basename($_FILES["photo"]["name"]);
    $targetFilePath = $targetDir . $fileName;
    $fileType = pathinfo($targetFilePath, PATHINFO_EXTENSION);

    if (!empty($name) && !empty($fileName)) {
        if (!file_exists($targetDir)) {
            mkdir($targetDir, 0777, true);
        }

        $allowedTypes = ['jpg', 'jpeg', 'png', 'gif'];
        if (in_array($fileType, $allowedTypes)) {
            if (move_uploaded_file($_FILES["photo"]["tmp_name"], $targetFilePath)) {
                $sql = "INSERT INTO indirect_code (code, name, photo) VALUES ('$code', '$name', '$fileName')";
                if ($connection->query($sql)) {
                    $msg = "Data berhasil ditambahkan melalui form! Kode: $code";
                } else {
                    $msg = "Gagal menambahkan data melalui form: " . $connection->error;
                }
            } else {
                $msg = "Gagal mengunggah foto.";
            }
        } else {
            $msg = "Format file tidak didukung. Hanya JPG, JPEG, PNG, dan GIF yang diperbolehkan.";
        }
    } else {
        $msg = "Nama dan foto wajib diisi.";
    }
}

// Proses untuk upload CSV
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['form_type']) && $_POST['form_type'] === 'csv_upload') {
    $fileTmpName = $_FILES['csv_file']['tmp_name'];
    $fileType = pathinfo($_FILES['csv_file']['name'], PATHINFO_EXTENSION);

    if (!empty($fileTmpName) && $fileType === 'csv') {
        if (($handle = fopen($fileTmpName, 'r')) !== FALSE) {
            fgetcsv($handle); // Melewati header CSV

            while (($data = fgetcsv($handle, 1000, ',')) !== FALSE) {
                $name = $connection->real_escape_string($data[0]);
                if (!empty($name)) {
                    $code = generateCode($connection);
                    $sql = "INSERT INTO indirect_code (code, name) VALUES ('$code', '$name')";
                    if (!$connection->query($sql)) {
                        $msg = "Gagal menambahkan data dari CSV: " . $connection->error;
                        break;
                    }
                }
            }
            fclose($handle);
            $msg = "Data berhasil ditambahkan melalui CSV!";
        } else {
            $msg = "Gagal membaca file CSV.";
        }
    } else {
        $msg = "Harap unggah file CSV yang valid.";
    }
}

// Proses untuk menghapus data
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_id'])) {
    $deleteId = intval($_POST['delete_id']);
    $stmt = $connection->prepare("SELECT photo FROM indirect_code WHERE id = ?");
    $stmt->bind_param("i", $deleteId);
    $stmt->execute();
    $result = $stmt->get_result();
    $row = $result->fetch_assoc();

    if (!empty($row['photo']) && file_exists("upload/indirect/" . $row['photo'])) {
        unlink("upload/indirect/" . $row['photo']);
    }

    $stmt = $connection->prepare("DELETE FROM indirect_code WHERE id = ?");
    $stmt->bind_param("i", $deleteId);
    if ($stmt->execute()) {
        $msg = "Data dengan ID $deleteId berhasil dihapus.";
    } else {
        $msg = "Gagal menghapus data: " . $connection->error;
    }
    $stmt->close();
}

// Proses untuk upload foto pada baris tertentu
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['upload_photo_id'])) {
    $photoId = intval($_POST['upload_photo_id']);
    $fileName = basename($_FILES["upload_photo"]["name"]);
    $targetFilePath = "upload/indirect/" . $fileName;
    $fileType = pathinfo($targetFilePath, PATHINFO_EXTENSION);

    if (!empty($fileName)) {
        $allowedTypes = ['jpg', 'jpeg', 'png', 'gif'];
        if (in_array($fileType, $allowedTypes)) {
            if (move_uploaded_file($_FILES["upload_photo"]["tmp_name"], $targetFilePath)) {
                // Update foto pada baris yang dipilih
                $stmt = $connection->prepare("UPDATE indirect_code SET photo = ? WHERE id = ?");
                $stmt->bind_param("si", $fileName, $photoId);
                if ($stmt->execute()) {
                    $msg = "Foto berhasil diupdate.";
                } else {
                    $msg = "Gagal mengupdate foto: " . $connection->error;
                }
                $stmt->close();
            } else {
                $msg = "Gagal mengunggah foto.";
            }
        } else {
            $msg = "Format file tidak didukung. Hanya JPG, JPEG, PNG, dan GIF yang diperbolehkan.";
        }
    } else {
        $msg = "Harap pilih foto untuk diupload.";
    }
}

// Pagination settings
$recordsPerPage = 10; // Jumlah record per halaman
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1; // Halaman saat ini
$offset = ($page - 1) * $recordsPerPage; // Offset untuk query SQL

// Search query
$searchQuery = isset($_GET['search']) ? $connection->real_escape_string($_GET['search']) : '';

// Menghitung total jumlah record
$totalRecordsQuery = "SELECT COUNT(*) AS total_records FROM indirect_code WHERE name LIKE '%$searchQuery%' OR code LIKE '%$searchQuery%'";
$totalRecordsResult = $connection->query($totalRecordsQuery);
$totalRecordsRow = $totalRecordsResult->fetch_assoc();
$totalRecords = $totalRecordsRow['total_records'];

// Menghitung total jumlah halaman
$totalPages = ceil($totalRecords / $recordsPerPage);

// Mengambil data untuk halaman saat ini
$query = "SELECT * FROM indirect_code WHERE name LIKE '%$searchQuery%' OR code LIKE '%$searchQuery%' LIMIT $offset, $recordsPerPage";
$result = $connection->query($query);
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Create Indirect Code</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.0/css/bootstrap.min.css">
    <!-- Untuk modal popup -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.0/css/bootstrap.min.css">
    <style>
        .modal-dialog {
            max-width: 80%;
        }

        .modal-body img {
            width: 100%;
            height: auto;
        }

        .btn-group {
            display: flex;
            gap: 10px;
        }

        .btn-group button {
            width: 100%; /* Tombol akan menyesuaikan dengan lebar kontainer */
        }

        /* Pagination Styles */
        .pagination {
            display: flex;
            justify-content: center;
            flex-wrap: wrap;
        }

        .pagination .page-item {
            margin: 0 5px;
        }

        .pagination .page-link {
            padding: 0.5rem 1rem;
        }

        .pagination .page-item.disabled .page-link {
            pointer-events: none;
            color: #6c757d;
            background-color: #fff;
            border-color: #dee2e6;
        }

        @media (max-width: 768px) {
            .pagination .page-item:not(.active):not(.disabled) {
                display: none;
            }

            .pagination .page-item.active,
            .pagination .page-item.disabled,
            .pagination .page-item:first-child,
            .pagination .page-item:last-child {
                display: block;
            }
        }
    </style>
</head>

<body>
    <div class="container mt-5">
        <!-- Home Button -->
        <div class="mb-3">
            <a href="purchase_indirect.php" class="btn btn-primary">Home</a>
        </div>

        <h2 class="text-center">Create Indirect Code</h2>

        <!-- Menampilkan pesan -->
        <?php if ($msg): ?>
            <div class="alert <?php echo strpos($msg, 'berhasil') !== false ? 'alert-success' : 'alert-danger'; ?>">
                <?php echo $msg; ?>
            </div>
        <?php endif; ?>

        <!-- Form Input Manual -->
        <form action="" method="POST" enctype="multipart/form-data">
            <input type="hidden" name="form_type" value="normal_form">
            <div class="mb-3">
                <label for="name" class="form-label">Name</label>
                <input type="text" id="name" name="name" class="form-control" required>
            </div>
            <div class="mb-3">
                <label for="photo" class="form-label">Upload Photo</label>
                <input type="file" id="photo" name="photo" class="form-control" accept=".jpg, .jpeg, .png, .gif" required>
            </div>
            <button type="submit" class="btn btn-primary">Add Indirect Code</button>
        </form>

        <!-- Form Upload CSV -->
        <form action="" method="POST" enctype="multipart/form-data" class="mt-5">
            <input type="hidden" name="form_type" value="csv_upload">
            <div class="mb-3">
                <label for="csv_file" class="form-label">Upload CSV File</label>
                <input type="file" id="csv_file" name="csv_file" class="form-control" accept=".csv" required>
            </div>
            <button type="submit" class="btn btn-success">Upload CSV</button>
        </form>

        <!-- Search Form -->
        <form action="" method="GET" class="mt-5">
            <div class="input-group mb-3">
                <input type="text" name="search" class="form-control" placeholder="Search by Name or Code" value="<?php echo htmlspecialchars($searchQuery); ?>">
                <button type="submit" class="btn btn-primary">Search</button>
            </div>
        </form>

        <h3 class="mt-5">Indirect Code List</h3>
        <table class="table table-bordered">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Code</th>
                    <th>Name</th>
                    <th>Photo</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php
                if ($result->num_rows > 0):
                    while ($row = $result->fetch_assoc()):
                ?>
                        <tr>
                            <td><?php echo $row['id']; ?></td>
                            <td><?php echo $row['code']; ?></td>
                            <td><?php echo $row['name']; ?></td>
                            <td>
                                <?php if ($row['photo']): ?>
                                    <button class="btn btn-info btn-sm" data-bs-toggle="modal" data-bs-target="#viewModal<?php echo $row['id']; ?>">View</button>
                                    <!-- Modal Pop-up View Foto -->
                                    <div class="modal fade" id="viewModal<?php echo $row['id']; ?>" tabindex="-1" aria-labelledby="viewModalLabel" aria-hidden="true">
                                        <div class="modal-dialog">
                                            <div class="modal-content">
                                                <div class="modal-header">
                                                    <h5 class="modal-title" id="viewModalLabel">View Photo</h5>
                                                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                                </div>
                                                <div class="modal-body">
                                                    <img src="upload/indirect/<?php echo $row['photo']; ?>" alt="Photo">
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                <?php else: ?>
                                    No photo
                                <?php endif; ?>
                            </td>
                            <td class="btn-group">
                                <form action="" method="POST" enctype="multipart/form-data">
                                    <input type="hidden" name="upload_photo_id" value="<?php echo $row['id']; ?>">
                                    <input type="file" name="upload_photo" accept=".jpg, .jpeg, .png, .gif" class="btn btn-warning btn-sm" required>
                                    <button type="submit" class="btn btn-warning btn-sm">Upload</button>
                                </form>
                                <form action="" method="POST" class="mt-2">
                                    <input type="hidden" name="delete_id" value="<?php echo $row['id']; ?>">
                                    <button type="submit" class="btn btn-danger btn-sm">Delete</button>
                                </form>
                            </td>
                        </tr>
                <?php
                    endwhile;
                endif;
                ?>
            </tbody>
        </table>

        <!-- Pagination Controls -->
        <nav aria-label="Page navigation">
            <ul class="pagination">
                <?php if ($page > 1): ?>
                    <li class="page-item">
                        <a class="page-link" href="?page=<?php echo $page - 1; ?>&search=<?php echo htmlspecialchars($searchQuery); ?>" aria-label="Previous">
                            <span aria-hidden="true">&laquo;</span>
                        </a>
                    </li>
                <?php endif; ?>

                <?php
                $startPage = max(1, $page - 2);
                $endPage = min($totalPages, $page + 2);

                if ($startPage > 1): ?>
                    <li class="page-item">
                        <a class="page-link" href="?page=1&search=<?php echo htmlspecialchars($searchQuery); ?>">1</a>
                    </li>
                    <?php if ($startPage > 2): ?>
                        <li class="page-item disabled">
                            <span class="page-link">...</span>
                        </li>
                    <?php endif; ?>
                <?php endif; ?>

                <?php for ($i = $startPage; $i <= $endPage; $i++): ?>
                    <li class="page-item <?php echo $i == $page ? 'active' : ''; ?>">
                        <a class="page-link" href="?page=<?php echo $i; ?>&search=<?php echo htmlspecialchars($searchQuery); ?>"><?php echo $i; ?></a>
                    </li>
                <?php endfor; ?>

                <?php if ($endPage < $totalPages): ?>
                    <?php if ($endPage < $totalPages - 1): ?>
                        <li class="page-item disabled">
                            <span class="page-link">...</span>
                        </li>
                    <?php endif; ?>
                    <li class="page-item">
                        <a class="page-link" href="?page=<?php echo $totalPages; ?>&search=<?php echo htmlspecialchars($searchQuery); ?>"><?php echo $totalPages; ?></a>
                    </li>
                <?php endif; ?>

                <?php if ($page < $totalPages): ?>
                    <li class="page-item">
                        <a class="page-link" href="?page=<?php echo $page + 1; ?>&search=<?php echo htmlspecialchars($searchQuery); ?>" aria-label="Next">
                            <span aria-hidden="true">&raquo;</span>
                        </a>
                    </li>
                <?php endif; ?>
            </ul>
        </nav>
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.0/js/bootstrap.bundle.min.js"></script>
</body>

</html>
