<?php
declare(strict_types=1);

use App\Core\Database;

return function (Database $db): void {
    $ts = date('Y-m-d H:i:s');
    $branches = $db->select("SELECT id, branch_code FROM branches");
    $quals = $db->select("SELECT id, code FROM qualifications");

    if (empty($branches) || empty($quals)) {
        return;
    }

    $branchMap = [];
    foreach ($branches as $b) {
        $branchMap[$b['branch_code']] = (int) $b['id'];
    }
    $qualMap = [];
    foreach ($quals as $q) {
        $qualMap[$q['code']] = (int) $q['id'];
    }

    // Current prices from 1/7/2024
    $prices = [
        // Sheraton
        ['branch' => 'sheraton', 'qual' => 'high',   'price' => '150000.00', 'from' => '2024-07-01'],
        ['branch' => 'sheraton', 'qual' => 'medium', 'price' => '225000.00', 'from' => '2024-07-01'],
        ['branch' => 'sheraton', 'qual' => 'none',   'price' => '300000.00', 'from' => '2024-07-01'],
        // 6th October
        ['branch' => 'sadis', 'qual' => 'high',   'price' => '150000.00', 'from' => '2024-07-01'],
        ['branch' => 'sadis', 'qual' => 'medium', 'price' => '225000.00', 'from' => '2024-07-01'],
        ['branch' => 'sadis', 'qual' => 'none',   'price' => '300000.00', 'from' => '2024-07-01'],
        // New Capital
        ['branch' => 'new_capital', 'qual' => 'high',   'price' => '150000.00', 'from' => '2024-07-01'],
        ['branch' => 'new_capital', 'qual' => 'medium', 'price' => '225000.00', 'from' => '2024-07-01'],
        ['branch' => 'new_capital', 'qual' => 'none',   'price' => '300000.00', 'from' => '2024-07-01'],

        // Previous prices before 1/7/2024
        ['branch' => 'sheraton', 'qual' => 'high',   'price' => '114000.00', 'from' => '2020-01-01', 'to' => '2024-06-30'],
        ['branch' => 'sheraton', 'qual' => 'medium', 'price' => '171000.00', 'from' => '2020-01-01', 'to' => '2024-06-30'],
        ['branch' => 'sheraton', 'qual' => 'none',   'price' => '228000.00', 'from' => '2020-01-01', 'to' => '2024-06-30'],
    ];

    foreach ($prices as $p) {
        $branchId = $branchMap[$p['branch']] ?? null;
        $qualId = $qualMap[$p['qual']] ?? null;
        if (!$branchId || !$qualId) {
            continue;
        }
        $existing = $db->selectOne(
            "SELECT id FROM pricing_configs WHERE branch_id = ? AND qualification_id = ? AND effective_from = ? AND membership_type = 'working'",
            [$branchId, $qualId, $p['from']]
        );
        if ($existing) {
            continue;
        }
        $db->insert('pricing_configs', [
            'branch_id'        => $branchId,
            'qualification_id' => $qualId,
            'membership_type'  => 'working',
            'price'            => $p['price'],
            'currency'         => 'EGP',
            'effective_from'   => $p['from'],
            'effective_to'     => $p['to'] ?? null,
            'is_active'        => 1,
            'created_at'       => $ts,
            'updated_at'       => $ts,
        ]);
    }
};