#!/usr/bin/perl -Ilibs
package API::ProductSaleAdmin;

use strict;
use warnings;

use JSON;
use Moose;
use Try::Tiny;
use Scalar::Util qw(blessed reftype);
use Carp;
use Data::Dumper;

use API::Controller ();
extends 'API::Controller';

use ECS::ProductSale;
use ECS::ProductSale::Brand;
use ECS::ProductSale::Vendor;
use ECS::ProductSale::Filter;
use ECS::ProductSale::Rule;
use ECS::ProductSale::Site;
use ECS::ProductSale::Condition;
use ECS::ProductSale::Action;
use ECS::ProductSale::FilterKey;
use ECS::ProductSale::ConditionKey;

__PACKAGE__->meta->make_immutable;

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

sub saleList {
    my $self = (shift)->new({'input' => shift || {}});
    $self->data->{'templates'} = [ "index.html" ];

    my $dbh = ECS::Site::fromName(ECS)->estore_dbhr;
    my $sales = ECS::ProductSale->new( dbh => $dbh );
    @{ $self->data->{'sales'}} = map { $_->TO_JSON } $sales->getAll( dbh => $dbh);

    return $self->result;
}

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

sub getSale {
    my $self = (shift)->new({'input' => shift || {}});
    $self->data->{'templates'} = [ "editor.html" ];

    my $dbh = ECS::Site::fromName(ECS)->estore_dbhr;
    my $productSale = ECS::ProductSale->new( dbh => $dbh )->get( $self->{'input'}->{'saleID'});
    
	$self->data->{'sale'} = $productSale->TO_JSON;

    # add brands
    my $brands = ECS::ProductSale::Brand->new( dbh => $dbh );
    @{ $self->data->{'brands'}} = map { $_->TO_JSON } $brands->getAll( dbh => $dbh);

    # add Filter keys
    my $filterKey = ECS::ProductSale::FilterKey->new( dbh => $dbh );
    @{ $self->data->{'filterKey'}} = map { $_->TO_JSON } $filterKey->getAll( dbh => $dbh);

    # add Condition keys
    my $conditionKey = ECS::ProductSale::ConditionKey->new( dbh => $dbh );
    @{ $self->data->{'conditionKey'}} = map { $_->TO_JSON } $conditionKey->getAll( dbh => $dbh);
    
    # add Vendors
    my $vendors = ECS::ProductSale::Vendor->new( dbh => $dbh );
    @{ $self->data->{'vendors'}} = map { $_->TO_JSON } $vendors->getAll( dbh => $dbh);

    return $self->result;
}

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

sub newSale {
    my $self = (shift)->new({'input' => shift || {}});
    $self->data->{'templates'} = [ "editor.html" ];

    my $dbh = ECS::Site::fromName(ECS)->estore_dbhr;
    my $productSale = ECS::ProductSale->new( dbh => $dbh );
    $self->data->{'sale'} = $productSale->newSaleTemplate;

    # add brands
    my $brands = ECS::ProductSale::Brand->new( dbh => $dbh );
    @{ $self->data->{'brands'}} = map { $_->TO_JSON } $brands->getAll( dbh => $dbh);

    # add Filter keys
    my $filterKey = ECS::ProductSale::FilterKey->new( dbh => $dbh );
    @{ $self->data->{'filterKey'}} = map { $_->TO_JSON } $filterKey->getAll( dbh => $dbh);

    # add Condition keys
    my $conditionKey = ECS::ProductSale::ConditionKey->new( dbh => $dbh );
    @{ $self->data->{'conditionKey'}} = map { $_->TO_JSON } $conditionKey->getAll( dbh => $dbh);
    
    # add Vendors
    my $vendors = ECS::ProductSale::Vendor->new( dbh => $dbh );
    @{ $self->data->{'vendors'}} = map { $_->TO_JSON } $vendors->getAll( dbh => $dbh);

    return $self->result;
}

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

sub saveSale {
    my $self = (shift)->new({'input' => shift || {}});

    my $dbh = ECS::Site::fromName(ECS)->estore_dbh;
    my $data = $self->input;

    my $saleID = $data->{'saleID'};
    my @siteIDs = $data->{'siteIDs'};
    my @filters = $data->{'filters'};
    my @rules = $data->{'rules'};
    my $description = $data->{'description'};
    my $startDate = $data->{'startDate'};
    my $endDate = $data->{'endDate'};
    my $status = $data->{'status'};
    my @saleSites = $data->{'saleSites'};

    my %sale = (
        'saleID' => $saleID,
        'siteIDs' => \@siteIDs,
        'status' => $status,
        'filters' => \@filters,
        'description' => $description,
        'rules' => \@rules,
        'endDate' => $endDate,
        'startDate' => $startDate,
        'saleSites' => @saleSites,
    );
    
    my ($success, $error);
    
    if ($saleID) {
        my $productSale = ECS::ProductSale
            ->new( dbh => $dbh )
            ->get($saleID);
        ($success, $error) = $productSale->save( \%sale );
    } else {
        ($success, $error) = ECS::ProductSale
            ->new( dbh => $dbh )
            ->save( \%sale );
    }
    
    if ($success) {
        $self->success(1);
    } else {
        $self->error( $error || "" );
    }
    return $self->getSale({ saleID => 1 })->{data};
}

###############################################################################
# 
sub copySale {
    my $self = (shift)->new({'input' => shift || {}});
    $self->data->{'templates'} = [ "editor.html" ];

    # Get the sale to be copied
    my $dbh = ECS::Site::fromName(ECS)->estore_dbhr;
    my $productSale = ECS::ProductSale->new( dbh => $dbh )->get( $self->{'input'}->{'saleID'});
	my $saleData = $productSale->TO_JSON;

    # Duplicate data into new hash
    my $newSaleData;
    $newSaleData->{endDate} = $productSale->endDate;
    $newSaleData->{startDate} = $productSale->startDate;
	$newSaleData->{status} = 'DRAFT';
    $newSaleData->{description} = $saleData->{description} . " (COPY)";

    $newSaleData->{siteIDs} = $saleData->{siteIDs};

    # remove saleID so we end up creating a new sale.
	$newSaleData->{saleID} = undef;

    # copy sale sites
    my @newSaleSites;
    foreach my $saleSite (@{$saleData->{saleSites}}) {
        my $newSite = $saleSite;
        $newSite->{saleID} = undef;
        $newSite->{saleSiteID} = undef;
        push @newSaleSites, $newSite;
    }
    push @{$newSaleData->{saleSites}}, @newSaleSites;
    
    # copy the hash keys that are NOT IDs, removing all existing IDs to treat this as a new sale
    # copy the filters
    my @newFilters;
    foreach my $filter (@{$saleData->{filters}}) {
        my $newFilter = $filter;
        $newFilter->{saleID} = undef;
        $newFilter->{saleFilterID} = undef;
        $newFilter->{filterValue}->{saleFilterID} = undef;
        $newFilter->{filterValue}->{saleFilterValueID} = undef;
        push @newFilters, $newFilter;
    }
    push @{$newSaleData->{filters}}, @newFilters;
    # copy the rules
    my @newRules;
    foreach my $rule (@{$saleData->{rules}}) {
        my $newRule = $rule;
        $newRule->{saleID} = undef;
        $newRule->{saleRuleID} = undef;
        $newRule->{ruleAction}->{saleRuleID} = undef if ($newRule->{ruleAction} != undef);
        $newRule->{ruleAction}->{saleActionID} = undef if ($newRule->{ruleAction} != undef);
        my @newConditions;
        foreach my $condition (@{$rule->{ruleCondition}}) {
            my $newCondition = $condition;
            $newCondition->{saleRuleID} = undef;
            $newCondition->{saleConditionID} = undef;
        }
        push @newRules, $newRule;
    }
    push @{$newSaleData->{rules}}, @newRules;

    $self->data->{sale} = $newSaleData;

    # add brands
    my $brands = ECS::ProductSale::Brand->new( dbh => $dbh );
    @{ $self->data->{'brands'}} = map { $_->TO_JSON } $brands->getAll( dbh => $dbh);

    # add Filter keys
    my $filterKey = ECS::ProductSale::FilterKey->new( dbh => $dbh );
    @{ $self->data->{'filterKey'}} = map { $_->TO_JSON } $filterKey->getAll( dbh => $dbh);

    # add Condition keys
    my $conditionKey = ECS::ProductSale::ConditionKey->new( dbh => $dbh );
    @{ $self->data->{'conditionKey'}} = map { $_->TO_JSON } $conditionKey->getAll( dbh => $dbh);
    
    # add Vendors
    my $vendors = ECS::ProductSale::Vendor->new( dbh => $dbh );
    @{ $self->data->{'vendors'}} = map { $_->TO_JSON } $vendors->getAll( dbh => $dbh);

    return $self->result;
}

###############################################################################
# 
sub deleteSale {
    my $self = (shift)->new({'input' => shift || {}});
    $self->data->{'templates'} = [ "index.html" ];
    my $saleID = $self->{'input'}->{'saleID'};
    
    # Get the sale to be deleted
    my $dbh = ECS::Site::fromName(ECS)->estore_dbh;
    my $productSale = ECS::ProductSale->new( dbh => $dbh )->get( $saleID );

    if ($productSale) {
        my ($success, $error) = $productSale->delete( $saleID );
        if ($success) {
            $self->success(1);
            $self->error( "" );
        } else {
            $self->success(0);
            $self->error("Unable to delete Sale, $saleID" );
        }
    }

    return saleList($self);
}    


1;
