<?php
require_once("../php/db_connect.php");

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

$owner_shop_id = isset($_SESSION["user_id"]) ? (int)$_SESSION["user_id"] : 0;

if ($owner_shop_id <= 0) {
    echo "<script>window.location='index.php';</script>";
    exit();
}

$message = $_GET["message"] ?? "";

function h($value) {
    return htmlspecialchars($value ?? "", ENT_QUOTES, "UTF-8");
}

/*
|--------------------------------------------------------------------------
| ADD SERVICE TYPE
|--------------------------------------------------------------------------
*/
if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST["add_type"])) {
    $type_name = trim($_POST["type_name"] ?? "");

    if ($type_name !== "") {
        $check = $conn->prepare("
            SELECT id 
            FROM service_type_options 
            WHERE owner_shop_id = ? 
              AND LOWER(type_name) = LOWER(?)
            LIMIT 1
        ");
        $check->bind_param("is", $owner_shop_id, $type_name);
        $check->execute();
        $checkResult = $check->get_result();

        if ($checkResult->num_rows > 0) {
            echo "<script>window.location='admin.php?page=service-types&message=type_exists';</script>";
            exit();
        }

        $stmt = $conn->prepare("
            INSERT INTO service_type_options 
            (owner_shop_id, type_name, status)
            VALUES (?, ?, 'active')
        ");
        $stmt->bind_param("is", $owner_shop_id, $type_name);
        $stmt->execute();

        echo "<script>window.location='admin.php?page=service-types&message=type_added';</script>";
        exit();
    }
}

/*
|--------------------------------------------------------------------------
| ADD SUBTYPE
|--------------------------------------------------------------------------
*/
if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST["add_subtype"])) {
    $service_type_id = isset($_POST["service_type_id"]) ? (int)$_POST["service_type_id"] : 0;
    $subtype_name = trim($_POST["subtype_name"] ?? "");

    if ($service_type_id > 0 && $subtype_name !== "") {
        $checkType = $conn->prepare("
            SELECT id 
            FROM service_type_options
            WHERE id = ?
              AND owner_shop_id = ?
              AND status = 'active'
            LIMIT 1
        ");
        $checkType->bind_param("ii", $service_type_id, $owner_shop_id);
        $checkType->execute();
        $typeResult = $checkType->get_result();

        if ($typeResult->num_rows === 0) {
            echo "<script>window.location='admin.php?page=service-types&message=invalid_type';</script>";
            exit();
        }

        $checkSubtype = $conn->prepare("
            SELECT id
            FROM service_subtype_options
            WHERE owner_shop_id = ?
              AND service_type_id = ?
              AND LOWER(subtype_name) = LOWER(?)
            LIMIT 1
        ");
        $checkSubtype->bind_param("iis", $owner_shop_id, $service_type_id, $subtype_name);
        $checkSubtype->execute();
        $subtypeResult = $checkSubtype->get_result();

        if ($subtypeResult->num_rows > 0) {
            echo "<script>window.location='admin.php?page=service-types&message=subtype_exists';</script>";
            exit();
        }

        $stmt = $conn->prepare("
            INSERT INTO service_subtype_options
            (owner_shop_id, service_type_id, subtype_name, status)
            VALUES (?, ?, ?, 'active')
        ");
        $stmt->bind_param("iis", $owner_shop_id, $service_type_id, $subtype_name);
        $stmt->execute();

        echo "<script>window.location='admin.php?page=service-types&message=subtype_added';</script>";
        exit();
    }
}

/*
|--------------------------------------------------------------------------
| TOGGLE SERVICE TYPE STATUS
|--------------------------------------------------------------------------
*/
if (isset($_GET["toggle_type"])) {
    $type_id = (int)$_GET["toggle_type"];

    $stmt = $conn->prepare("
        UPDATE service_type_options
        SET status = IF(status = 'active', 'inactive', 'active')
        WHERE id = ?
          AND owner_shop_id = ?
    ");
    $stmt->bind_param("ii", $type_id, $owner_shop_id);
    $stmt->execute();

    echo "<script>window.location='admin.php?page=service-types&message=type_updated';</script>";
    exit();
}

/*
|--------------------------------------------------------------------------
| TOGGLE SUBTYPE STATUS
|--------------------------------------------------------------------------
*/
if (isset($_GET["toggle_subtype"])) {
    $subtype_id = (int)$_GET["toggle_subtype"];

    $stmt = $conn->prepare("
        UPDATE service_subtype_options
        SET status = IF(status = 'active', 'inactive', 'active')
        WHERE id = ?
          AND owner_shop_id = ?
    ");
    $stmt->bind_param("ii", $subtype_id, $owner_shop_id);
    $stmt->execute();

    echo "<script>window.location='admin.php?page=service-types&message=subtype_updated';</script>";
    exit();
}

/*
|--------------------------------------------------------------------------
| FETCH SERVICE TYPES FOR THIS SHOP ONLY
|--------------------------------------------------------------------------
*/
$typeStmt = $conn->prepare("
    SELECT id, type_name, status
    FROM service_type_options
    WHERE owner_shop_id = ?
    ORDER BY type_name ASC
");
$typeStmt->bind_param("i", $owner_shop_id);
$typeStmt->execute();
$types_result = $typeStmt->get_result();

$service_types = [];
while ($row = $types_result->fetch_assoc()) {
    $service_types[] = $row;
}

/*
|--------------------------------------------------------------------------
| FETCH SUBTYPES FOR THIS SHOP ONLY
|--------------------------------------------------------------------------
*/
$subtypeStmt = $conn->prepare("
    SELECT 
        sso.id,
        sso.subtype_name,
        sso.status,
        sto.type_name
    FROM service_subtype_options sso
    INNER JOIN service_type_options sto 
        ON sso.service_type_id = sto.id
    WHERE sso.owner_shop_id = ?
      AND sto.owner_shop_id = ?
    ORDER BY sto.type_name ASC, sso.subtype_name ASC
");
$subtypeStmt->bind_param("ii", $owner_shop_id, $owner_shop_id);
$subtypeStmt->execute();
$subtypes_result = $subtypeStmt->get_result();
?>

<div class="container-fluid px-0 service-types-page">

    <div class="d-flex justify-content-between align-items-center flex-wrap gap-3 mb-4">
        <div>
            <h1 class="fw-bold mb-1">Manage Service Types</h1>
            <p class="text-muted mb-0">
                Add and manage service types and subtypes for your own shop only.
            </p>
        </div>

        <a href="admin.php?page=services" class="btn btn-light border rounded-pill px-4">
            <i class="fa-solid fa-arrow-left me-1"></i> Back to Services
        </a>
    </div>

    <?php if ($message === "type_added"): ?>
        <div class="alert alert-success rounded-3">Service type added successfully.</div>
    <?php elseif ($message === "subtype_added"): ?>
        <div class="alert alert-success rounded-3">Subtype added successfully.</div>
    <?php elseif ($message === "type_exists"): ?>
        <div class="alert alert-warning rounded-3">This service type already exists.</div>
    <?php elseif ($message === "subtype_exists"): ?>
        <div class="alert alert-warning rounded-3">This subtype already exists under the selected service type.</div>
    <?php elseif ($message === "type_updated"): ?>
        <div class="alert alert-success rounded-3">Service type status updated.</div>
    <?php elseif ($message === "subtype_updated"): ?>
        <div class="alert alert-success rounded-3">Subtype status updated.</div>
    <?php elseif ($message === "invalid_type"): ?>
        <div class="alert alert-danger rounded-3">Invalid service type selected.</div>
    <?php endif; ?>

    <div class="row g-4 mb-4">

        <div class="col-lg-6">
            <div class="card border-0 shadow-sm rounded-4 h-100">
                <div class="card-body p-4">

                    <h4 class="fw-bold mb-2">Add Service Type</h4>
                    <p class="text-muted small mb-4">
                        Example: Printing, Tailoring, Embroidery, Layout Design.
                    </p>

                    <form method="POST">
                        <div class="mb-3">
                            <label class="form-label fw-semibold">Service Type Name</label>
                            <input 
                                type="text" 
                                name="type_name" 
                                class="form-control" 
                                placeholder="Enter service type"
                                required
                            >
                        </div>

                        <button type="submit" name="add_type" class="btn btn-primary px-4">
                            Add Type
                        </button>
                    </form>

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

        <div class="col-lg-6">
            <div class="card border-0 shadow-sm rounded-4 h-100">
                <div class="card-body p-4">

                    <h4 class="fw-bold mb-2">Add Subtype</h4>
                    <p class="text-muted small mb-4">
                        Example: Logo Embroidery, Name Embroidery, Custom Design Embroidery.
                    </p>

                    <form method="POST">
                        <div class="mb-3">
                            <label class="form-label fw-semibold">Select Service Type</label>
                            <select name="service_type_id" class="form-select" required>
                                <option value="">Select Service Type</option>

                                <?php foreach ($service_types as $type): ?>
                                    <?php if ($type["status"] === "active"): ?>
                                        <option value="<?php echo (int)$type["id"]; ?>">
                                            <?php echo h($type["type_name"]); ?>
                                        </option>
                                    <?php endif; ?>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="mb-3">
                            <label class="form-label fw-semibold">Subtype Name</label>
                            <input 
                                type="text" 
                                name="subtype_name" 
                                class="form-control" 
                                placeholder="Enter subtype"
                                required
                            >
                        </div>

                        <button type="submit" name="add_subtype" class="btn btn-primary px-4">
                            Add Subtype
                        </button>
                    </form>

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

    </div>

    <div class="row g-4">

        <div class="col-lg-5">
            <div class="card border-0 shadow-sm rounded-4">
                <div class="card-body p-4">

                    <h4 class="fw-bold mb-3">Service Types</h4>

                    <div class="table-responsive">
                        <table class="table table-hover align-middle service-type-table mb-0">
                            <thead>
                                <tr>
                                    <th>Type Name</th>
                                    <th>Status</th>
                                    <th>Action</th>
                                </tr>
                            </thead>

                            <tbody>
                                <?php if (!empty($service_types)): ?>
                                    <?php foreach ($service_types as $type): ?>
                                        <tr>
                                            <td class="fw-semibold">
                                                <?php echo h($type["type_name"]); ?>
                                            </td>

                                            <td>
                                                <?php if ($type["status"] === "active"): ?>
                                                    <span class="badge bg-success-subtle text-success rounded-pill px-3 py-2">
                                                        Active
                                                    </span>
                                                <?php else: ?>
                                                    <span class="badge bg-secondary-subtle text-secondary rounded-pill px-3 py-2">
                                                        Inactive
                                                    </span>
                                                <?php endif; ?>
                                            </td>

                                            <td>
                                                <a 
                                                    href="admin.php?page=service-types&toggle_type=<?php echo (int)$type["id"]; ?>"
                                                    class="btn btn-sm btn-outline-secondary"
                                                    onclick="return confirm('Update this service type status?')"
                                                >
                                                    Toggle
                                                </a>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php else: ?>
                                    <tr>
                                        <td colspan="3">
                                            <div class="empty-state">
                                                <i class="fa-solid fa-list"></i>
                                                <p class="mb-0">No service types found.</p>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>

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

        <div class="col-lg-7">
            <div class="card border-0 shadow-sm rounded-4">
                <div class="card-body p-4">

                    <h4 class="fw-bold mb-3">Subtypes</h4>

                    <div class="table-responsive">
                        <table class="table table-hover align-middle service-type-table mb-0">
                            <thead>
                                <tr>
                                    <th>Service Type</th>
                                    <th>Subtype Name</th>
                                    <th>Status</th>
                                    <th>Action</th>
                                </tr>
                            </thead>

                            <tbody>
                                <?php if ($subtypes_result && $subtypes_result->num_rows > 0): ?>
                                    <?php while ($row = $subtypes_result->fetch_assoc()): ?>
                                        <tr>
                                            <td>
                                                <?php echo h($row["type_name"]); ?>
                                            </td>

                                            <td class="fw-semibold">
                                                <?php echo h($row["subtype_name"]); ?>
                                            </td>

                                            <td>
                                                <?php if ($row["status"] === "active"): ?>
                                                    <span class="badge bg-success-subtle text-success rounded-pill px-3 py-2">
                                                        Active
                                                    </span>
                                                <?php else: ?>
                                                    <span class="badge bg-secondary-subtle text-secondary rounded-pill px-3 py-2">
                                                        Inactive
                                                    </span>
                                                <?php endif; ?>
                                            </td>

                                            <td>
                                                <a 
                                                    href="admin.php?page=service-types&toggle_subtype=<?php echo (int)$row["id"]; ?>"
                                                    class="btn btn-sm btn-outline-secondary"
                                                    onclick="return confirm('Update this subtype status?')"
                                                >
                                                    Toggle
                                                </a>
                                            </td>
                                        </tr>
                                    <?php endwhile; ?>
                                <?php else: ?>
                                    <tr>
                                        <td colspan="4">
                                            <div class="empty-state">
                                                <i class="fa-solid fa-layer-group"></i>
                                                <p class="mb-0">No subtypes found.</p>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>

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

    </div>

</div>

<style>
.service-types-page {
    width: 100%;
}

.service-types-page h1 {
    font-size: clamp(26px, 2vw, 36px);
    color: #111827;
}

.form-control,
.form-select {
    border-radius: 10px;
    padding: 10px 12px;
}

.service-type-table thead th {
    background: #f8fafc;
    color: #111827;
    font-size: 14px;
    font-weight: 700;
    padding: 14px;
    white-space: nowrap;
    border-bottom: 1px solid #e5e7eb;
}

.service-type-table tbody td {
    padding: 14px;
    font-size: 14px;
    border-bottom: 1px solid #f0f0f0;
    vertical-align: middle;
}

.service-type-table tbody tr:hover {
    background: #f9fbff;
}

.empty-state {
    padding: 35px 10px;
    text-align: center;
    color: #6b7280;
}

.empty-state i {
    font-size: 30px;
    color: #9ca3af;
    margin-bottom: 10px;
}

@media (max-width: 768px) {
    .service-type-table {
        min-width: 600px;
    }
}
</style>