<?php
session_start();
require_once '../config/database.php';

if (!isset($_SESSION["user_id"]) || $_SESSION["role"] !== "admin") {
    header("Location: ../auth/login.php");
    exit;
}

if (!isset($_GET["id"]) || !is_numeric($_GET["id"])) {
    header("Location: partners.php");
    exit;
}

$id = (int) $_GET["id"];
$error = "";
$success = "";

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

$stmt = $pdo->prepare("SELECT * FROM partner_shops WHERE id = ? LIMIT 1");
$stmt->execute([$id]);
$partner = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$partner) {
    die("Partner shop not found.");
}

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $shop_name = trim($_POST["shop_name"] ?? "");
    $owner_name = trim($_POST["owner_name"] ?? "");
    $phone = trim($_POST["phone"] ?? "");
    $email = trim($_POST["email"] ?? "");
    $address = trim($_POST["address"] ?? "");
    $status = $_POST["status"] ?? "inactive";

    $latitude = trim($_POST["latitude"] ?? "");
    $longitude = trim($_POST["longitude"] ?? "");

    $latitude = $latitude === "" ? null : $latitude;
    $longitude = $longitude === "" ? null : $longitude;

    if ($shop_name === "" || $email === "") {
        $error = "Shop name and email are required.";
    } elseif (!in_array($status, ["active", "inactive"], true)) {
        $error = "Invalid status.";
    } else {
        try {
            $stmt = $pdo->prepare("
                UPDATE partner_shops
                SET shop_name = ?,
                    owner_name = ?,
                    phone = ?,
                    email = ?,
                    address = ?,
                    latitude = ?,
                    longitude = ?,
                    status = ?
                WHERE id = ?
            ");

            $stmt->execute([
                $shop_name,
                $owner_name,
                $phone,
                $email,
                $address,
                $latitude,
                $longitude,
                $status,
                $id
            ]);

            $success = "Partner shop updated successfully.";

            $stmt = $pdo->prepare("SELECT * FROM partner_shops WHERE id = ? LIMIT 1");
            $stmt->execute([$id]);
            $partner = $stmt->fetch(PDO::FETCH_ASSOC);

        } catch (PDOException $e) {
            $error = "Database error: " . $e->getMessage();
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Edit Partner Shop</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <style>
        * {
            box-sizing: border-box;
        }

        body {
            margin: 0;
            font-family: Inter, Arial, sans-serif;
            background: #f4f6f9;
            color: #1f2937;
        }

        .page {
            max-width: 1100px;
            margin: 40px auto;
            padding: 0 20px;
        }

        .page-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 24px;
        }

        .page-header h1 {
            margin: 0;
            font-size: 28px;
            font-weight: 700;
        }

        .back-link {
            text-decoration: none;
            color: #2563eb;
            font-weight: 600;
        }

        .card {
            background: #ffffff;
            border-radius: 18px;
            padding: 28px;
            box-shadow: 0 10px 30px rgba(15, 23, 42, 0.08);
        }

        .alert {
            padding: 14px 16px;
            border-radius: 12px;
            margin-bottom: 18px;
            font-weight: 600;
        }

        .alert-error {
            background: #fee2e2;
            color: #991b1b;
        }

        .alert-success {
            background: #dcfce7;
            color: #166534;
        }

        .form-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 20px;
        }

        .form-group {
            display: flex;
            flex-direction: column;
        }

        .form-group.full {
            grid-column: 1 / -1;
        }

        label {
            font-size: 14px;
            font-weight: 600;
            margin-bottom: 8px;
            color: #374151;
        }

        input,
        textarea,
        select {
            width: 100%;
            padding: 12px 14px;
            border: 1px solid #d1d5db;
            border-radius: 12px;
            font-size: 15px;
            background: #ffffff;
        }

        input:focus,
        textarea:focus,
        select:focus {
            outline: none;
            border-color: #2563eb;
            box-shadow: 0 0 0 4px rgba(37, 99, 235, 0.12);
        }

        input:disabled {
            background: #f3f4f6;
            color: #6b7280;
        }

        textarea {
            min-height: 110px;
            resize: vertical;
        }

        .map-box {
            margin-top: 24px;
            padding: 18px;
            border-radius: 14px;
            background: #f9fafb;
            border: 1px dashed #d1d5db;
        }

        .map-actions {
            display: flex;
            flex-wrap: wrap;
            gap: 12px;
            margin-bottom: 10px;
        }

        .map-actions a {
            text-decoration: none;
            color: #2563eb;
            font-weight: 600;
        }

        .tip {
            margin: 0;
            font-size: 14px;
            color: #6b7280;
        }

        .actions {
            display: flex;
            justify-content: flex-end;
            gap: 12px;
            margin-top: 28px;
        }

        .btn {
            border: none;
            border-radius: 12px;
            padding: 12px 18px;
            font-size: 15px;
            font-weight: 700;
            cursor: pointer;
            text-decoration: none;
        }

        .btn-primary {
            background: #2563eb;
            color: white;
        }

        .btn-secondary {
            background: #e5e7eb;
            color: #374151;
        }

        @media (max-width: 768px) {
            .page-header {
                flex-direction: column;
                align-items: flex-start;
                gap: 10px;
            }

            .form-grid {
                grid-template-columns: 1fr;
            }

            .actions {
                flex-direction: column-reverse;
            }

            .btn {
                width: 100%;
                text-align: center;
            }
        }
    </style>
</head>

<body>
<div class="page">

    <div class="page-header">
        <h1>Edit Partner Shop</h1>
        <a class="back-link" href="partners.php">← Back to Partner Shops</a>
    </div>

    <div class="card">

        <?php if ($error): ?>
            <div class="alert alert-error"><?php echo e($error); ?></div>
        <?php endif; ?>

        <?php if ($success): ?>
            <div class="alert alert-success"><?php echo e($success); ?></div>
        <?php endif; ?>

        <form method="POST" action="edit_partner.php?id=<?php echo $id; ?>">
            <div class="form-grid">

                <div class="form-group">
                    <label>Shop Code</label>
                    <input type="text" value="<?php echo e($partner["shop_code"]); ?>" disabled>
                </div>

                <div class="form-group">
                    <label>Status</label>
                    <select name="status">
                        <option value="active" <?php echo ($partner["status"] === "active") ? "selected" : ""; ?>>
                            Active
                        </option>
                        <option value="inactive" <?php echo ($partner["status"] === "inactive") ? "selected" : ""; ?>>
                            Inactive
                        </option>
                    </select>
                </div>

                <div class="form-group">
                    <label>Shop Name</label>
                    <input type="text" name="shop_name" value="<?php echo e($partner["shop_name"]); ?>" required>
                </div>

                <div class="form-group">
                    <label>Owner Name</label>
                    <input type="text" name="owner_name" value="<?php echo e($partner["owner_name"]); ?>">
                </div>

                <div class="form-group">
                    <label>Phone</label>
                    <input type="text" name="phone" value="<?php echo e($partner["phone"]); ?>">
                </div>

                <div class="form-group">
                    <label>Email / Login Email</label>
                    <input type="email" name="email" value="<?php echo e($partner["email"]); ?>" required>
                </div>

                <div class="form-group full">
                    <label>Address</label>
                    <textarea name="address"><?php echo e($partner["address"]); ?></textarea>
                </div>

                <div class="form-group">
                    <label>Latitude</label>
                    <input type="text" name="latitude" value="<?php echo e($partner["latitude"]); ?>">
                </div>

                <div class="form-group">
                    <label>Longitude</label>
                    <input type="text" name="longitude" value="<?php echo e($partner["longitude"]); ?>">
                </div>

            </div>

            <div class="map-box">
                <div class="map-actions">
                    <?php if (!empty($partner["latitude"]) && !empty($partner["longitude"])): ?>
                        <a target="_blank"
                           href="https://maps.google.com/?q=<?php echo e($partner["latitude"]); ?>,<?php echo e($partner["longitude"]); ?>">
                            Open Current Location
                        </a>
                    <?php endif; ?>

                    <a target="_blank" href="https://maps.google.com">
                        Find Location on Google Maps
                    </a>
                </div>

                <p class="tip">
                    Tip: Open Google Maps, right click the shop location, then copy latitude and longitude.
                </p>
            </div>

            <div class="actions">
                <a href="partners.php" class="btn btn-secondary">Cancel</a>
                <button type="submit" class="btn btn-primary">Update Partner Shop</button>
            </div>
        </form>

    </div>
</div>
<?php require __DIR__ . '/../config/auto_update.php'; ?>
</body>
</html>