#!/usr/bin/perl
# Temporary script for updating match_retail kits on TMS,
# should be rolled into price_update.cgi in the future.

use strict;
use warnings;

use lib qw(libs);
BEGIN {
    use API::Config;
    use lib $API::Config::Config->{'Website_libs'};
};

use ECS::DB;
use ECS::dbConfig;
use ECS::Site;

{
    my $p = init();
    main($p);
}

exit;

###############################################################################

sub init {
    my $p = {};

    $p->{'dbh'} = ECS::DB->connect({ 'config' => $ECS::dbConfig::db{'mysql'} });
	$p->{'dbhr'} = ECS::DB->connect({'config' => $ECS::dbConfig::db{'mysqlSlave'}, readonly => 1})
    $p->{'tmsSite'} = ECS::Site->fromName("TMS");

    return $p;
}

###############################################################################

sub main {
    my ($p) = @_;

    $p->{'pricing'} = getPricing($p);
    setPricing($p);

    return;
}

###############################################################################

sub getPricing {
    my ($p) = @_;

    my $productVendor = $p->{'tmsSite'}->prefix . ".productVendor";

    my $sql = qq{
        SELECT
            product.productID,
            siteProductVendor.price_retail,
            SUM(componentSiteProductVendor.price_retail * productComponent.qtyRequired) AS componentRetail
        FROM product
        JOIN $productVendor AS siteProductVendor
            ON product.productID = siteProductVendor.productID
        JOIN productComponent
            ON product.productID = productComponent.productID
        JOIN product AS componentProduct
            ON productComponent.componentProductID = componentProduct.productID
        JOIN productVendor AS componentProductVendor
            ON componentProduct.productID = componentProductVendor.productID
            AND componentProductVendor.currentVendor = 'YES'
        JOIN $productVendor AS componentSiteProductVendor
            ON componentProduct.productID = componentSiteProductVendor.productID
            AND componentSiteProductVendor.vendorID = componentProductVendor.vendorID
        WHERE
            siteProductVendor.markup_method = 'markup_matchretail'
        GROUP BY
            product.productID
        HAVING
            price_retail <> componentRetail
    };
    my $sth = $p->{'dbhr'}->prepare($sql);
    $sth->execute;
    return $sth->fetchall_arrayref({});
}

###############################################################################

sub setPricing {
    my ($p) = @_;

    my $sql = q{
        UPDATE
            productVendor
        SET
            price_retail = ?
        WHERE
            productID = ?
            AND vendorID = 0
    };
    my $sth = $p->{'tmsSite'}->site_dbh->prepare($sql);

    for my $product (@{ $p->{'pricing'} }) {
        $sth->execute(
            $product->{'componentRetail'},
            $product->{'productID'},
        );
    }

    return;
}

###############################################################################

