<?php
include 'includes/config.php';
session_start();

if (!$_SESSION['email']) {
    header('location:login.php');
}
// --- Folder check for logo upload ---
$uploadDir = __DIR__ . "/uploads/companies/";
if (!is_dir($uploadDir)) {
    mkdir($uploadDir, 0777, true);
}

// --- Insert / Update Company ---
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $id      = $_POST['id'] ?? null;
    $name    = $_POST['name'];
    $address = $_POST['address'];
    $phone   = $_POST['phone'];
    $email   = $_POST['email'];

    // --- File Upload ---
    $logoPath = null;
    if (!empty($_FILES['logo']['name'])) {
        $fileName = time() . "_" . basename($_FILES['logo']['name']);
        $target   = $uploadDir . $fileName;
        if (move_uploaded_file($_FILES['logo']['tmp_name'], $target)) {
            $logoPath = "uploads/companies/" . $fileName;
        }
    }

    if ($id) {
        // --- Update ---
        if ($logoPath) {
            $sql = "UPDATE companies SET name=?, address=?, phone=?, email=?, logo=? WHERE id=?";
            $stmt = $conn->prepare($sql);
            $stmt->execute([$name, $address, $phone, $email, $logoPath, $id]);
        } else {
            $sql = "UPDATE companies SET name=?, address=?, phone=?, email=? WHERE id=?";
            $stmt = $conn->prepare($sql);
            $stmt->execute([$name, $address, $phone, $email, $id]);
        }
    } else {
        // --- Insert ---
        $sql = "INSERT INTO companies (name, address, phone, email, logo) VALUES (?,?,?,?,?)";
        $stmt = $conn->prepare($sql);
        $stmt->execute([$name, $address, $phone, $email, $logoPath]);
    }
    echo "<script>window.location.href='list_company.php';</script>";
    exit;
}

// --- Delete Company ---
if (isset($_GET['delete'])) {
    $id = $_GET['delete'];
    $stmt = $conn->prepare("DELETE FROM companies WHERE id=?");
    $stmt->execute([$id]);
    echo "<script>window.location.href='list_company.php';</script>";
    exit;
}

// --- Fetch Companies ---
$companies = $conn->query("SELECT * FROM companies ORDER BY id DESC")->fetchAll(PDO::FETCH_ASSOC);
?>
?>
<!doctype html>
<html lang="en">


<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>List Company</title>
    <!-- Favicon -->
    <link rel="shortcut icon" href="images/favicon.ico" />
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <!-- Typography CSS -->
    <link rel="stylesheet" href="css/typography.css">
    <!-- Style CSS -->
    <link rel="stylesheet" href="css/style.css">
    <!-- Responsive CSS -->
    <link rel="stylesheet" href="css/responsive.css">
    <style>
        ion-icon {
            font-size: 20px;
            margin-bottom: -5px;
        }
    </style>
</head>

<body>
    <!-- loader Start -->
    <div id="loading">
        <div id="loading-center">
        </div>
    </div>
    <!-- loader END -->
    <!-- Wrapper Start -->
    <div class="wrapper">
        <!-- Sidebar  -->
        <?php
        include 'includes/sidebar.php';
        ?>
        <!-- TOP Nav Bar -->
        <?php include 'includes/header.php'; ?>
        <!-- TOP Nav Bar END -->
        <!-- Page Content  -->
        <div id="content-page" class="content-page">
            <div class="container-fluid">
                <div class="row">
                    <div class="col-sm-12">
                        <div class="iq-card">
                            <div class="iq-card-header d-flex justify-content-between row">
                                <div class="iq-header-title col-lg-6">
                                    <h4 class="card-title"><a href="list_expense.php">Company</a> > List Company
                                    </h4>
                                </div>
                                <div class="col-lg-6">
                                    <button class="btn btn-primary  ps-5 pe-5" style="float:inline-end;">
                                        <a href="" class="text-white">
                                            <ion-icon name="add-outline" style="font-size:20px; margin-bottom:-4px">
                                            </ion-icon> Add
                                        </a>
                                    </button>
                                </div>
                            </div>
                            <!-- search bar -->
                          

                            <div class="iq-card-body" style="overflow:auto;">
                                
                            <form method="POST" enctype="multipart/form-data" class="mb-4">
    <input type="hidden" name="id" id="company_id">
    <div class="row mb-2">
        <div class="col"><input type="text" name="name" id="name" class="form-control" placeholder="Company Name" required></div>
        <div class="col"><input type="text" name="phone" id="phone" class="form-control" placeholder="Phone"></div>
    </div>
    <div class="row mb-2">
        <div class="col"><input type="email" name="email" id="email" class="form-control" placeholder="Email"></div>
        <div class="col"><input type="file" name="logo" id="logo" class="form-control"></div>
    </div>
    <textarea name="address" id="address" class="form-control mb-2" placeholder="Address"></textarea>
    <button type="submit" class="btn btn-success">Save</button>
</form>

<!-- Search -->
<input type="text" id="searchInput" onkeyup="searchTable()" class="form-control mb-3" placeholder="Search company...">

<!-- Table -->
<table id="companyTable" class="table table-bordered table-hover">
    <thead class="table-light">
        <tr>
            <th>#</th>
            <th>Logo</th>
            <th>Name</th>
            <th>Phone</th>
            <th>Email</th>
            <th>Address</th>
            <th>Actions</th>
        </tr>
    </thead>
    <tbody>
        <?php foreach ($companies as $c): ?>
        <tr>
            <td><?= $c['id'] ?></td>
            <td><?php if($c['logo']) echo "<img src='{$c['logo']}' width='50'>"; ?></td>
            <td><?= htmlspecialchars($c['name']) ?></td>
            <td><?= htmlspecialchars($c['phone']) ?></td>
            <td><?= htmlspecialchars($c['email']) ?></td>
            <td><?= nl2br(htmlspecialchars($c['address'])) ?></td>
            <td>
                <a href="list_company.php?delete=<?= $c['id'] ?>" class="btn btn-danger btn-sm" onclick="return confirm('Delete this company?')">Delete</a>
            </td>
        </tr>
        <?php endforeach; ?>
    </tbody>
</table>

                            </div>
                        </div>
                    </div>
                </div>
            </div>

        </div>
    </div>
    </div>
    <!-- Wrapper END -->
    <!-- Footer -->
    <footer class="iq-footer">
        <div class="container-fluid">
            <div class="row">
                <div class="col-lg-6">
                    <ul class="list-inline mb-0">
                        <li class="list-inline-item"><a href="privacy-policy.html">Privacy Policy</a></li>
                        <li class="list-inline-item"><a href="terms-of-service.html">Terms of Use</a></li>
                    </ul>
                </div>
                <div class="col-lg-6 text-right">
                    Copyright <span id="copyright">
                        <script>
                            document.getElementById('copyright').appendChild(document.createTextNode(new Date()
                                .getFullYear()))
                        </script>
                    </span> <a href="#">Vito</a> All Rights Reserved.
                </div>
            </div>
        </div>
    </footer>
    <nav class="iq-float-menu">
        <input type="checkbox" href="#" class="iq-float-menu-open" name="menu-open" id="menu-open" />
        <label class="iq-float-menu-open-button" for="menu-open">
            <span class="lines line-1"></span>
            <span class="lines line-2"></span>
            <span class="lines line-3"></span>
        </label>
        <button class="iq-float-menu-item bg-info" data-toggle="tooltip" data-placement="top" title="Direction Mode"
            data-mode="rtl"><i class="ri-text-direction-r"></i></button>
        <button class="iq-float-menu-item bg-danger" data-toggle="tooltip" data-placement="top" title="Color Mode"
            id="dark-mode" data-active="true"><i class="ri-sun-line"></i></button>
        <button class="iq-float-menu-item bg-warning" data-toggle="tooltip" data-placement="top" title="Comming Soon"><i
                class="ri-palette-line"></i></button>
    </nav>
    <!-- Footer END -->
    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="js/jquery.min.js"></script>
    <!-- Rtl and Darkmode -->
    <script src="js/rtl.js"></script>
    <script src="js/customizer.js"></script>
    <script src="js/popper.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
    <!-- Appear JavaScript -->
    <script src="js/jquery.appear.js"></script>
    <!-- Countdown JavaScript -->
    <script src="js/countdown.min.js"></script>
    <!-- Counterup JavaScript -->
    <script src="js/waypoints.min.js"></script>
    <script src="js/jquery.counterup.min.js"></script>
    <!-- Wow JavaScript -->
    <script src="js/wow.min.js"></script>
    <!-- Apexcharts JavaScript -->
    <script src="js/apexcharts.js"></script>
    <!-- Slick JavaScript -->
    <script src="js/slick.min.js"></script>
    <!-- Select2 JavaScript -->
    <script src="js/select2.min.js"></script>
    <!-- Owl Carousel JavaScript -->
    <script src="js/owl.carousel.min.js"></script>
    <!-- Magnific Popup JavaScript -->
    <script src="js/jquery.magnific-popup.min.js"></script>
    <!-- Smooth Scrollbar JavaScript -->
    <script src="js/smooth-scrollbar.js"></script>
    <!-- lottie JavaScript -->
    <script src="js/lottie.js"></script>
    <!-- Chart Custom JavaScript -->
    <script src="js/chart-custom.js"></script>
    <!-- Custom JavaScript -->
    <script src="js/custom.js"></script>
</body>

</html>