<?php include "header.php"; ?>
<?php include "sidebar.php"; ?>

<div class="main-content">
    <div class="page-content">
        <div class="container-fluid">

            <!-- Page Title -->
            <div class="row">
                <div class="col-12">
                    <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                        <h4 class="mb-sm-0">آپلود تقسیم اوقات</h4>
                        <div class="page-title-right">
                            <ol class="breadcrumb m-0">
                                <li class="breadcrumb-item active">اضافه</li>
                            </ol>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Upload & Table Section -->
            <div class="row">
                <div class="col-xxl-9">
                    <div class="card mt-xxl-n5">
                        <div class="card-header">
                            <ul class="nav nav-tabs-custom rounded card-header-tabs border-bottom-0" role="tablist">
                                <li class="nav-item">
                                    <a class="nav-link active" data-bs-toggle="tab" href="#uploadTab" role="tab" aria-selected="true">
                                        <i class="fas fa-upload"></i> آپلود تقسیم اوقات
                                    </a>
                                </li>
                            </ul>
                        </div>

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

                        $status = "OK";
                        $msg = "";
                        $successmsg = "";

                        // Handle Deletion
                        if (isset($_GET['delete_id'])) {
                            $delete_id = intval($_GET['delete_id']);
                            $stmt = $con->prepare("SELECT ufile FROM time_table WHERE t_id = ?");
                            $stmt->bind_param("i", $delete_id);
                            $stmt->execute();
                            $result = $stmt->get_result();
                            if ($result && $result->num_rows > 0) {
                                $row = $result->fetch_assoc();
                                $file_to_delete = $row['ufile'];
                                $file_path = 'uploads/' . $file_to_delete;
                                if (file_exists($file_path)) {
                                    unlink($file_path);
                                }
                            }
                            $stmt->close();

                            $del_stmt = $con->prepare("DELETE FROM time_table WHERE t_id = ?");
                            $del_stmt->bind_param("i", $delete_id);
                            if ($del_stmt->execute()) {
                                $successmsg = "<div class='alert alert-success alert-dismissible alert-outline fade show'>
                                    تصویر با موفقیت حذف شد.
                                    <button type='button' class='btn-close' data-bs-dismiss='alert' aria-label='Close'></button>
                                    </div>";
                            } else {
                                $msg = "خطا در حذف تصویر: " . $del_stmt->error;
                                $status = "NOTOK";
                            }
                            $del_stmt->close();
                        }

                        // Handle Upload
                        if (isset($_POST['import'])) {
                            $allowed = ['jpg', 'jpeg', 'png', 'gif'];

                            if (isset($_FILES['excel']) && $_FILES['excel']['error'] == 0) {
                                $file_name = $_FILES['excel']['name'];
                                $file_tmp = $_FILES['excel']['tmp_name'];
                                $ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));

                                if (in_array($ext, $allowed)) {
                                    $uploads_dir = 'uploads/';
                                    if (!is_dir($uploads_dir)) {
                                        mkdir($uploads_dir, 0755, true);
                                    }
                                    $random_digit = rand(1000, 9999);
                                    $new_file_name = $random_digit . "_" . basename($file_name);
                                    $upload_path = $uploads_dir . $new_file_name;

                                    if (move_uploaded_file($file_tmp, $upload_path)) {
                                        $save_name = $new_file_name;
                                        $stmt = $con->prepare("INSERT INTO time_table (ufile) VALUES (?)");
                                        if ($stmt) {
                                            $stmt->bind_param("s", $save_name);
                                            if ($stmt->execute()) {
                                                $successmsg = "<div class='alert alert-success alert-dismissible alert-outline fade show'>
                                                    تصویر با موفقیت آپلود شد.
                                                    <button type='button' class='btn-close' data-bs-dismiss='alert' aria-label='Close'></button>
                                                    </div>";
                                            } else {
                                                $msg = "خطا در ذخیره اطلاعات در پایگاه داده: " . $stmt->error;
                                                $status = "NOTOK";
                                            }
                                            $stmt->close();
                                        } else {
                                            $msg = "خطا در آماده‌سازی پرس و جو: " . $con->error;
                                            $status = "NOTOK";
                                        }
                                    } else {
                                        $msg = "خطا در آپلود فایل.";
                                        $status = "NOTOK";
                                    }
                                } else {
                                    $msg = "فقط فرمت‌های jpg، jpeg، png و gif مجاز هستند.";
                                    $status = "NOTOK";
                                }
                            } else {
                                $msg = "فایل انتخاب نشده یا خطا در آپلود فایل.";
                                $status = "NOTOK";
                            }
                        }
                        ?>

                        <div class="card-body p-4">
                            <div class="tab-content">
                                <div class="tab-pane active" id="uploadTab" role="tabpanel">

                                    <!-- Messages -->
                                    <?php
                                    if ($_SERVER['REQUEST_METHOD'] == 'POST' || isset($_GET['delete_id'])) {
                                        if ($status == "OK") {
                                            echo $successmsg;
                                        } else {
                                            echo "<div class='alert alert-danger alert-dismissible alert-outline fade show'>
                                                $msg
                                                <button type='button' class='btn-close' data-bs-dismiss='alert' aria-label='Close'></button>
                                                </div>";
                                        }
                                    }
                                    ?>

                                    <!-- Upload Form -->
                                    <form action="" method="post" enctype="multipart/form-data">
                                        <div class="row">
                                            <div class="col-lg-6">
                                                <div class="mb-3">
                                                    <label for="fileInput" class="form-label">انتخاب فایل تصویر</label>
                                                    <input type="file" name="excel" id="fileInput" class="form-control" required>
                                                </div>
                                            </div>
                                            <div class="col-lg-6 d-flex align-items-end">
                                                <button type="submit" name="import" class="btn btn-primary">آپلود</button>
                                            </div>
                                        </div>
                                    </form>

                                    <!-- Images Table -->
                                    <div class="table-responsive mt-4">
                                        <table class="table table-striped table-bordered" id="example" dir="rtl">
                                            <thead class="text-center">
                                                <tr>
                                                    <th>تصویر</th>
                                                    <th>عملیات</th>
                                                </tr>
                                            </thead>
                                            <tbody class="text-center">
                                                <?php
                                                $q = "SELECT * FROM time_table ORDER BY t_id DESC";
                                                $r = $con->query($q);
                                                if ($r && $r->num_rows > 0) {
                                                    while ($row = $r->fetch_assoc()) {
                                                        $ufile = htmlspecialchars($row['ufile']);
                                                        $t_id = intval($row['t_id']);
                                                        echo "<tr>";
                                                        echo "<td><img src='uploads/{$ufile}' style='max-height:100px;' alt='تصویر'></td>";
                                                        echo "<td>
                                                                <a href='?delete_id={$t_id}' 
                                                                   class='btn btn-danger btn-sm' 
                                                                   onclick='return confirm(\"آیا مطمئن هستید که می‌خواهید این تصویر را حذف کنید؟\")'>
                                                                   حذف
                                                                </a>
                                                              </td>";
                                                        echo "</tr>";
                                                    }
                                                } else {
                                                    echo "<tr><td colspan='2'>هیچ تصویری یافت نشد.</td></tr>";
                                                }
                                                ?>
                                            </tbody>
                                        </table>
                                    </div>

                                </div> <!-- tab-pane -->
                            </div> <!-- tab-content -->
                        </div> <!-- card-body -->
                    </div> <!-- card -->
                </div> <!-- col -->
            </div> <!-- row -->

        </div> <!-- container-fluid -->
    </div> <!-- page-content -->

<?php include "footer.php"; ?>
