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

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

$error = "";
$success = "";

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"]);

    if ($shop_name === "" || $owner_name === "" || $phone === "" || $email === "") {
        $error = "Shop name, owner name, phone and email are required.";
    } elseif (!preg_match('/^[0-9]{8,15}$/', $phone)) {
        $error = "Please enter a valid phone number. Use numbers only, 8 to 15 digits.";
    } else {
        $checkEmail = $pdo->prepare("SELECT id FROM users WHERE email = ? LIMIT 1");
        $checkEmail->execute([$email]);

        $checkPhone = $pdo->prepare("SELECT id FROM partner_shops WHERE phone = ? LIMIT 1");
        $checkPhone->execute([$phone]);

        if ($checkEmail->fetch()) {
            $error = "This email already exists.";
        } elseif ($checkPhone->fetch()) {
            $error = "This phone number already exists.";
        } else {
            try {
                $pdo->beginTransaction();

                $password_hash = password_hash("partner123", PASSWORD_DEFAULT);

                $stmt = $pdo->prepare("
                    INSERT INTO users (name, phone, email, password, role, status)
                    VALUES (?, ?, ?, ?, 'partner', 'active')
                ");
                $stmt->execute([$owner_name, $phone, $email, $password_hash]);

                $user_id = $pdo->lastInsertId();
                $shop_code = "SHOP" . str_pad($user_id, 6, "0", STR_PAD_LEFT);

                $stmt = $pdo->prepare("
                    INSERT INTO partner_shops 
                    (user_id, shop_code, shop_name, owner_name, phone, email, address)
                    VALUES (?, ?, ?, ?, ?, ?, ?)
                ");
                $stmt->execute([
                    $user_id,
                    $shop_code,
                    $shop_name,
                    $owner_name,
                    $phone,
                    $email,
                    $address
                ]);

                $pdo->commit();

                $success = "Partner shop created successfully. Shop Code: " . $shop_code . ". Login password: partner123";
            } catch (Exception $e) {
                $pdo->rollBack();
                $error = "Error: " . $e->getMessage();
            }
        }
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Create Partner Shop</title>

    <style>
        body {
            font-family: Arial, sans-serif;
            background: #f4f6f8;
            margin: 0;
            padding: 30px;
        }

        .container {
            max-width: 760px;
            margin: auto;
        }

        .card {
            background: #ffffff;
            border-radius: 14px;
            padding: 28px;
            box-shadow: 0 4px 14px rgba(0,0,0,0.08);
        }

        h1 {
            margin-top: 0;
            color: #111827;
        }

        .subtitle {
            color: #6b7280;
            margin-bottom: 22px;
        }

        label {
            font-weight: bold;
            color: #374151;
            display: block;
            margin-bottom: 6px;
        }

        input, textarea {
            width: 100%;
            padding: 12px;
            border: 1px solid #d1d5db;
            border-radius: 8px;
            font-size: 15px;
            box-sizing: border-box;
        }

        textarea {
            min-height: 100px;
        }

        .form-group {
            margin-bottom: 18px;
        }

        .required {
            color: #dc2626;
        }

        .hint {
            font-size: 13px;
            color: #6b7280;
            margin-top: 6px;
        }

        .info-box {
            background: #eff6ff;
            padding: 14px;
            border-radius: 10px;
            margin-bottom: 22px;
            color: #1e3a8a;
        }

        .success {
            color: #15803d;
            background: #dcfce7;
            padding: 12px;
            border-radius: 8px;
        }

        .error {
            color: #b91c1c;
            background: #fee2e2;
            padding: 12px;
            border-radius: 8px;
        }

        .actions {
            display: flex;
            gap: 10px;
            margin-top: 22px;
            flex-wrap: wrap;
        }

        .btn {
            padding: 11px 16px;
            border-radius: 8px;
            border: none;
            text-decoration: none;
            display: inline-block;
            font-size: 14px;
            cursor: pointer;
        }

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

        .btn-gray {
            background: #6b7280;
            color: white;
        }
    </style>
</head>

<body>

<div class="container">
    <div class="card">

        <h1>Create Partner Shop</h1>
        <p class="subtitle">Create a partner shop and login account.</p>

        <div class="info-box">
            Shop code will be generated automatically. Default partner login password is <strong>partner123</strong>.
        </div>

        <?php if ($error): ?>
            <p class="error"><?php echo htmlspecialchars($error); ?></p>
        <?php endif; ?>

        <?php if ($success): ?>
            <p class="success"><?php echo htmlspecialchars($success); ?></p>
        <?php endif; ?>

        <form method="POST">

            <div class="form-group">
                <label>Shop Name <span class="required">*</span></label>
                <input type="text" name="shop_name" required>
            </div>

            <div class="form-group">
                <label>Owner Name <span class="required">*</span></label>
                <input type="text" name="owner_name" required>
            </div>

            <div class="form-group">
                <label>Phone Number <span class="required">*</span></label>
                <input type="text" name="phone" required>
                <div class="hint">Numbers only, 8 to 15 digits.</div>
            </div>

            <div class="form-group">
                <label>Email / Login Email <span class="required">*</span></label>
                <input type="email" name="email" required>
            </div>

            <div class="form-group">
                <label>Address</label>
                <textarea name="address"></textarea>
            </div>

            <div class="actions">
                <button class="btn btn-primary" type="submit">Create Partner Shop</button>
                <a class="btn btn-gray" href="partners.php">Back to Partner Shops</a>
            </div>

        </form>

    </div>
</div>

</body>
</html>