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

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

$id = (int)($_GET["id"] ?? 0);

if ($id <= 0) {
    die("Invalid partner ID.");
}

$newPassword = "123456";
$hashedPassword = password_hash($newPassword, PASSWORD_DEFAULT);

try {
    $stmt = $pdo->prepare("
        SELECT id, user_id, shop_name, owner_name, email
        FROM partner_shops
        WHERE id = ?
        LIMIT 1
    ");
    $stmt->execute([$id]);
    $partner = $stmt->fetch(PDO::FETCH_ASSOC);

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

    if (empty($partner["email"])) {
        die("This partner has no email. Please add email first.");
    }

    $userId = $partner["user_id"];

    if (empty($userId)) {
        $stmt = $pdo->prepare("
            SELECT id
            FROM users
            WHERE email = ?
            LIMIT 1
        ");
        $stmt->execute([$partner["email"]]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($user) {
            $userId = $user["id"];
        } else {
            $stmt = $pdo->prepare("
                INSERT INTO users (name, email, password, role)
                VALUES (?, ?, ?, ?)
            ");

            $stmt->execute([
                $partner["owner_name"] ?: $partner["shop_name"],
                $partner["email"],
                $hashedPassword,
                "partner"
            ]);

            $userId = $pdo->lastInsertId();
        }

        $stmt = $pdo->prepare("
            UPDATE partner_shops
            SET user_id = ?
            WHERE id = ?
        ");
        $stmt->execute([$userId, $id]);
    }

    $stmt = $pdo->prepare("
        UPDATE users
        SET password = ?
        WHERE id = ?
    ");
    $stmt->execute([$hashedPassword, $userId]);

    header("Location: partners.php?password_reset=1");
    exit;

} catch (PDOException $e) {
    die("Database error: " . $e->getMessage());
}