<?php

//the global file operation
session_start();
ob_start();
//global varable



global $showoutside;

//to check if the page from .htacess
//$showoutside = $_GET['sn'];
// get the config file
include_once("../public/config.php");

//here the db files that include in the file
include("../public/include_dao.php");


//get the do the action
$do = $_GET['do'];



//Bank
$myBank = new Bank();
$myBankDAO = new BankMySqlDAO();
$myBankEx = new BankMySqlExtDAO();

//Bankaccount
$myBankaccount = new Bankaccount();
$myBankaccountDAO = new BankaccountMySqlDAO();
$myBankaccountEx = new BankaccountMySqlExtDAO();

$bind = new Bind();
$bindDAO = new BindMySqlDAO();
$bindEx = new BindMySqlExtDAO();

$bindSettlement = new Bindsettlement();
$bindSettlementDAO = new BindsettlementMySqlDAO();
$bindSettlementEx = new BindsettlementMySqlExtDAO();

$employee = new Employee();
$employeeDAO = new EmployeeMySqlDAO();
$employeeEX = new EmployeeMySqlExtDAO();


//user
$user = new User();
$userDAO = new UserMySqlDAO();
$userEX = new UserMySqlExtDAO();


$save = new Save();
$saveDAO = new SaveMySqlDAO();

$expensesType = new Expensestype();
$expensesTypeDAO = new ExpensestypeMySqlDAO();

//Costcenter
$costCenter = new Costcenter();
$costCenterDAO = new CostcenterMySqlDAO();
$costCenterEX = new CostcenterMySqlExtDAO();

$clientArea = new Clientarea();
$clientAreaDAO = new ClientareaMySqlDAO();
$clientAreaEX = new ClientareaMySqlExtDAO();

// insurancecompanies
$insuranceCompany = new Insurancecompanie();
$insuranceCompanyDAO = new InsurancecompaniesMySqlDAO();

//bill
$bills = new Bill();
$billsDAO = new BillsMySqlDAO();
$billsEX = new BillsMySqlExtDAO();

// branch
$branch = new Branch();
$branchDAO = new BranchMySqlDAO();


if ($do == "patientsearch") {
    $clientAreaId = filter_input(INPUT_POST, "clientArea");
    $insuranceCompanyId = filter_input(INPUT_POST, "insuranceCompany");
    $branchId = filter_input(INPUT_POST, "branchId");
    $clientId = filter_input(INPUT_POST, "clientId");
    $searchDateFrom = filter_input(INPUT_POST, "searchDateFrom");
    //$searchDateTo = filter_input(INPUT_POST, "searchDateTo");
    ## company name
    $clientArea = $clientAreaDAO->load($clientAreaId);
    $smarty->assign("clientArea", $clientArea);

    ## insurance Company name
    $insuranceCompany = $insuranceCompanyDAO->load($insuranceCompanyId);
    $smarty->assign("insuranceCompany", $insuranceCompany);

    ## insurance Company name
    $branch = $branchDAO->load($branchId);
    $smarty->assign("branch", $branch);


    ## get  clients of this company  which make bills in this month and payed by specific insurance company
    getBillsPat($clientAreaId, $insuranceCompanyId, $branchId, $searchDateFrom, $clientId);


    ## search month
    if ($searchDateFrom) {
        $batchMonthFrom = getBatchMonthAr($searchDateFrom);
        $smarty->assign("batchMonthFrom", $batchMonthFrom);
    }

//    if ($searchDateTo) {
//        $batchMonthTo = getBatchMonthAr($searchDateTo);
//        $smarty->assign("batchMonthTo", $batchMonthTo);
//    }

    $smarty->assign("today", date('Y-m-d'));
    $smarty->display("reportsview/patientsresult.html"); //the template page
}


##
elseif ($do == "companysearch") {
    $clientAreaId = filter_input(INPUT_POST, "clientArea");
    $insuranceCompanyId = filter_input(INPUT_POST, "insuranceCompany");
    $branchId = filter_input(INPUT_POST, "branchId");
    $searchDateFrom = filter_input(INPUT_POST, "searchDateFrom");

    ## get   company  which make bills in this month and payed by specific insurance company
    getBillsCompany($clientAreaId, $insuranceCompanyId, $branchId, $searchDateFrom);

    ## insurance Company name
    $branch = $branchDAO->load($branchId);
    $smarty->assign("branch", $branch);


    ## search month
    if ($searchDateFrom) {
        $batchMonthFrom = getBatchMonthAr($searchDateFrom);
        $smarty->assign("batchMonthFrom", $batchMonthFrom);
    }

    $smarty->assign("today", date('Y-m-d'));
    $smarty->display("reportsview/companyresult.html"); //the template page
}

##
elseif ($do == "inscompanysearch") {
    $insuranceCompanyId = filter_input(INPUT_POST, "insuranceCompany");
    $branchId = filter_input(INPUT_POST, "branchId");
    $searchDateFrom = filter_input(INPUT_POST, "searchDateFrom");


    ## get   company  which make bills in this month and payed by specific insurance company
    getBillsInsCompany($insuranceCompanyId, $branchId, $searchDateFrom);

    ## insurance Company name
    $branch = $branchDAO->load($branchId);
    $smarty->assign("branch", $branch);


    ## search month
    if ($searchDateFrom) {
        $batchMonthFrom = getBatchMonthAr($searchDateFrom);
        $smarty->assign("batchMonthFrom", $batchMonthFrom);
    }

    $smarty->assign("today", date('Y-m-d'));
    $smarty->display("reportsview/insresult.html"); //the template page
}

##
elseif ($do == "getbankaccounts") {
    $bankId = filter_input(INPUT_POST, "bankId");

    ## Bankaccount
    $myBankaccount = $myBankaccountEx->queryByBankidAndaccountdele($bankId);

    $result = '<option value="-1"> اختر </option>';

    foreach ($myBankaccount as $account) {
        $result .= '<option value="' . $account->accountid . '">' . $account->accountname . '</option>';
    }

    echo $result;
}


##
elseif ($do == "paymethodsearch") {
    $searchDateFrom = filter_input(INPUT_POST, "searchDateFrom");
    $searchDateTo = filter_input(INPUT_POST, "searchDateTo");
    $branchid = filter_input(INPUT_POST, "branchid");

    $qDate = '';
    if ($searchDateFrom && $searchDateTo) {
        $qDate = 'and  billdate  >= "' . $searchDateFrom . ' 00-00-00" and billdate <= "' . $searchDateTo . ' 23-59-55" ';
    } else {
        if ($searchDateFrom) {
            $qDate = 'and   billdate  >= "' . $searchDateFrom . ' 00-00-00" ';
        }
        if ($searchDateTo) {
            $qDate = 'and   billdate  <= "' . $searchDateTo . ' 23-59-55"';
        }
    }

    if (isset($branchid) && !empty($branchid)) {
        $qDate .= ' and branchid = ' . $branchid . ' ';
    }

    ## get sum of money paid by insurance company in bills
    $bIns = $billsEX->sumOfMoneyPaidByInsCompany($qDate);
    if (is_null($bIns->networkname)) {
        $bIns->networkname = 0;
    }
    $insPayed = $bIns->networkname;
    $smarty->assign("insPayed", $insPayed);


    ## get sum of money paid by networks in bills
    $bNet = $billsEX->sumOfMoneyPaidByNetworks($qDate);
    if (is_null($bNet->networkname)) {
        $bNet->networkname = 0;
    }
    $netPayed = $bNet->networkname;
    $smarty->assign("netPayed", $netPayed);



    ## get sum of money paid by insurance company in bills
    $bCash = $billsEX->sumOfMoneyPaidByCash($qDate);
    if (is_null($bCash->networkname)) {
        $bCash->networkname = 0;
    }
    $cashPayed = $bCash->networkname;
    $smarty->assign("cashPayed", $cashPayed);



    ## get sum of money paid by insurance company in bills
    $bWait = $billsEX->sumOfMoneyPaidByWait($qDate);
    if (is_null($bWait->networkname)) {
        $bWait->networkname = 0;
    }
    $waitPayed = $bWait->networkname;
    $smarty->assign("waitPayed", $waitPayed);

    $smarty->display("reportsview/paymethodresult.html"); //the template page
}


##
elseif ($do == "bindssearch") {
    $employeeId = filter_input(INPUT_POST, "employeeId");


    $binds = $bindEx->queryByEmployeeidAndDeleted($employeeId, 0);
    foreach ($binds as $bind) {
        $employee = $employeeDAO->load($bind->employeeid);
        $bind->employeeid = $employee->employeeName;

        $user = $userDAO->load($bind->userid);
        $bind->userid = $user->username;

        if ($bind->bindtype == 1) {
            $bind->bindtype = 'خزينة';
        } else {
            $bind->bindtype = 'بنك';
            $bind->savevalue = $bind->ckekvalue;
        }
    }
    $smarty->assign('binds', $binds);

    $smarty->display("bindview/searchresult.html"); //the template page
}


##
elseif ($do == "bindsettlesearch") {
    $employeeId = filter_input(INPUT_POST, "employeeId");
    $bindSettlements = array();

    $groups = $bindSettlementEx->getDistinctGroupNo($employeeId, 0);

    foreach ($groups as $groupNo) {
        $bindSettlement = $bindSettlementEx->queryByEmployeeidAndDeletedAndGroupno($employeeId, 0, $groupNo->groupno);

        $sumBindS = 0;

        foreach ($bindSettlement as $bindSett) {
            $employee = $employeeDAO->load($bindSett->employeeid);
            $bindSett->settlementway = $employee->employeeName;

            $user = $userDAO->load($bindSett->userid);
            $bindSett->userid = $user->username;

            $sumBindS = $sumBindS + $bindSett->value;

//            if ($bindSett->settlementway == 1) {
//                $bindSett->settlementway = 'خزينة';
//
//                $save = $saveDAO->load($bindSett->settlementwayid);
//                $bindSett->settlementwayid = $save->savename;
//            } else {
//                $bindSett->settlementway = 'مصروفات';
//                $bindSett->settlementway = $bindSett->ckekvalue;
//
//                $expensesType = $expensesTypeDAO->load($bindSett->settlementwayid);
//                $bindSett->settlementwayid = $expensesType->expensestypename;
//            }
        }
        $bindSettlement[0]->value = $sumBindS;
        array_push($bindSettlements, $bindSettlement);
    }

    $smarty->assign('binds', $bindSettlements);

    $smarty->display("bindsettlementview/searchresult.html"); //the template page
}


##
elseif ($do == "bindreportsearch") {
    $employeeId = filter_input(INPUT_POST, "employeeId");
    $fromDate = filter_input(INPUT_POST, "fromDate");
    $toDate = filter_input(INPUT_POST, "toDate");

    $q1 = '';
    $sumBind = 0;
    $sumSettlement = 0;

    if ($employeeId != -1) {
        $q1 .= 'and employeeid =' . $employeeId . ' ';
    }


    if ($fromDate && $toDate) {
        $q1 .= 'and  binddate  >= "' . $fromDate . '" and binddate <= "' . $toDate . '" ';
    } else {
        if ($fromDate) {
            $q1 .= 'and  binddate  >= ' . $fromDate . ' ';
        }
        if ($toDate) {
            $q1 .= 'and  binddate  <= ' . $toDate . ' ';
        }
    }

    $binds = $bindEx->searchBinds(0, $q1);
    $bindSettlement = $bindSettlementEx->queryByEmployeeidAndDeleted($employeeId, 0);

    foreach ($binds as $bind) {
        if ($bind->bindtype == 1) {
            $bind->bindtype = 'خزينة';
        } else {
            $bind->bindtype = 'بنك';
            $bind->savevalue = $bind->ckekvalue;
        }

        $sumBind = $sumBind + $bind->savevalue;
    }

    foreach ($bindSettlement as $bindSett) {
        if ($bindSett->settlementway == 1) {
            $bindSett->settlementway = 'خزينة';

            $save = $saveDAO->load($bindSett->settlementwayid);
            $bindSett->settlementwayid = $save->savename;
        } else {
            $bindSett->settlementway = 'مصروفات';
            $bindSett->settlementwayid = $bindSett->ckekvalue;

            $expensesType = $expensesTypeDAO->load($bindSett->settlementwayid);
            $bindSett->settlementwayid = $expensesType->expensestypename;
        }
        $sumSettlement = $sumSettlement + $bindSett->value;
    }

    $smarty->assign('binds', $binds);
    $smarty->assign('bindSettlements', $bindSettlement);

    $diff = $sumBind - $sumSettlement;

    $smarty->assign('sumBind', $sumBind);
    $smarty->assign('sumSettlement', $sumSettlement);
    $smarty->assign('diff', $diff);


    $smarty->display("bindsettlementview/searchresultreport.html"); //the template page
}

##
elseif ($do == "getbindvalue") {
    $employeeId = filter_input(INPUT_POST, "employeeId");


    $binds = $bindEx->queryByEmployeeidAndDeleted($employeeId, 0);
    $bindSettlements = $bindSettlementEx->queryByEmployeeidAndDeleted($employeeId, 0);

    $sumBind = 0;
    $sumSettlement = 0;

    $result = array();

    foreach ($bindSettlements as $bindSettlement) {
        $sumSettlement = $sumSettlement + $bindSettlement->value;
    }


    foreach ($binds as $bind) {
        ## external
        if ($bind->bindtype == 1) {
            $sumBind = $sumBind + $bind->savevalue;
        }
        ## internal
        else {
            $sumBind = $sumBind + $bind->ckekvalue;
        }
    }

    $sumNet = $sumBind - $sumSettlement;

    $result['sumNet'] = $sumNet;
    $result['sumSettlement'] = $sumSettlement;
    $result['sumBind'] = $sumBind;

    echo json_encode($result);
}

##
elseif ($do == "addnewsettle") {
    $itr = filter_input(INPUT_POST, "newItr");
    $smarty->assign("itr", $itr);

    ## save
    $save = $saveDAO->queryByConditions(0);
    $smarty->assign('saves', $save);

    ## expensesType
    $expensesType = $expensesTypeDAO->queryByCondition(0); //not deleted
    $smarty->assign("expensesType", $expensesType);

    ## Project
    $costCenter = $costCenterDAO->queryByCondation(0); //not deleted
    $smarty->assign("projects", $costCenter);


    $smarty->display("bindsettlementview/newsettle.html"); //the template page
}

function getBillsPat($clientAreaId, $insuranceCompanyId, $branchId, $searchDateFrom, $clientId) {
    global $billsEX;
    global $smarty;

    $totalAccept = 0;
    $totalDiscount = 0;
    $totalCarry = 0;
    $totalNet = 0;
    $branchQuery = '';
    $dateFromQuery = '';
    $clientIdQuery = '';

    if ($branchId != -1) {
        $branchQuery = 'and b.branchid  =' . $branchId . ' ';
    }
    if ($searchDateFrom != '') {
        $dateFromQuery = 'and b.billdate like "' . $searchDateFrom . '-%"';
    }
    if ($clientId != -1) {
        $clientIdQuery = 'and c.clientid  =' . $clientId . ' ';
    }

    $result = array();


    $companyClientsBills = $billsEX->getBillsByClientCompanyIdAndInsuranceCompanyId($clientAreaId, $insuranceCompanyId, $branchQuery, $dateFromQuery, $clientIdQuery, '', '');
    foreach ($companyClientsBills as $bill) {
        $bill->networkname = ($bill->companyaccept * ($bill->insdiscountpercent) / 100);  ##  insurance company discount value
        $bill->username = $bill->companyaccept - $bill->networkname - $bill->customercarry;    ## net required insurance from company

        $totalAccept += $bill->companyaccept;
        $totalDiscount += $bill->networkname;
        $totalCarry += $bill->customercarry;
        $totalNet += $bill->username;
    }

    $smarty->assign("totalAccept", $totalAccept);
    $smarty->assign("totalDiscount", $totalDiscount);
    $smarty->assign("totalCarry", $totalCarry);
    $smarty->assign("totalNet", $totalNet);
    $smarty->assign("companyClientsBills", $companyClientsBills);
    $smarty->assign("count", count($companyClientsBills));

    $result['totalAccept'] = $totalAccept;
    $result['totalDiscount'] = $totalDiscount;
    $result['totalCarry'] = $totalCarry;
    $result['totalNet'] = $totalNet;
    $result['companyClientsBills'] = companyClientsBills;
    return $result;
}

function getBatchMonthAr($searchDate) {
    $result = explode("-", $searchDate);
    $monthId = $result[1];
    $month = getmonthnamear($monthId);

    $array = str_split($result[0], 2);
    $year = $array[1];

    $batchMonth = $month . ' - ' . $year;
    return $batchMonth;
}

function getBatchMonthEn($searchDate) {
    $result = explode("-", $searchDate);
    $monthId = $result[1];
    $month = getmonthname($monthId);

    $array = str_split($result[0], 2);
    $year = $array[1];

    $batchMonth = $month . ' - ' . $year;
    return $batchMonth;
}

function getmonthname($monthId) {

    switch ($monthId) {
        case 1:
            $monthName = 'January';
            break;
        case 2:
            $monthName = 'February';
            break;
        case 3:
            $monthName = 'March';
            break;
        case 4:
            $monthName = 'April';
            break;
        case 5:
            $monthName = 'May';
            break;
        case 6:
            $monthName = 'June';
            break;
        case 7:
            $monthName = 'July';
            break;
        case 8:
            $monthName = 'August';
            break;
        case 9:
            $monthName = 'September';
            break;
        case 10:
            $monthName = 'October';
            break;
        case 11:
            $monthName = 'November';
            break;
        case 12:
            $monthName = 'December';
            break;
        default:
            $monthName = ' ';
            break;
    }
    return $monthName;
}

function getmonthnamear($monthId) {
    switch ($monthId) {
        case 1:
            $monthName = 'يناير';
            break;
        case 2:
            $monthName = 'فبراير';
            break;
        case 3:
            $monthName = 'مارس';
            break;
        case 4:
            $monthName = 'أبريل';
            break;
        case 5:
            $monthName = 'مايو';
            break;
        case 6:
            $monthName = 'يونيو';
            break;
        case 7:
            $monthName = 'يوليو';
            break;
        case 8:
            $monthName = 'أغسطس';
            break;
        case 9:
            $monthName = 'سبتمبر';
            break;
        case 10:
            $monthName = 'أكتوبر';
            break;
        case 11:
            $monthName = 'نوفمبر';
            break;
        case 12:
            $monthName = 'ديسمبر';
            break;
        default:
            $monthName = ' ';
            break;
    }
    return $monthName;
}

function getBillsCompany($clientAreaId, $insuranceCompanyId, $branchId, $searchDateFrom) {
    global $billsEX;
    global $smarty;


    $totalAccept = 0;
    $totalDiscount = 0;
    $totalCarry = 0;
    $totalNet = 0;

    $result = array();

    $companys = getDistinctCompanies($clientAreaId, $insuranceCompanyId, $branchId, $searchDateFrom);
    $branchQuery = '';
    $dateFromQuery = '';
    $joinQuery = 'join clientarea a        on a.id = c.clientareaid';
    $joinQuery1 = ', a.name as companyname';

    if ($branchId != -1) {
        $branchQuery = 'and b.branchid  =' . $branchId . ' ';
    }
    if ($searchDateFrom != '') {
        $dateFromQuery = 'and b.billdate like "' . $searchDateFrom . '-%"';
    }


    foreach ($companys as $company) {
        $i = 1;
        $companyClientsBills = $billsEX->getBillsByClientCompanyIdAndInsuranceCompanyId($company->clientareaid, $insuranceCompanyId, $branchQuery, $dateFromQuery, '', $joinQuery, $joinQuery1);
        foreach ($companyClientsBills as $bill) {
            if ($i == 1) {
                $company->totalAccept = 0;
                $company->totalDiscount = 0;
                $company->totalCarry = 0;
                $company->totalNet = 0;
                $company->companyname = $bill->companyname;
            }

            $bill->networkname = ($bill->companyaccept * ($bill->insdiscountpercent) / 100);  ##  insurance company discount value
            $bill->username = $bill->companyaccept - $bill->networkname - $bill->customercarry;    ## net required insurance from company

            $company->totalAccept = $company->totalAccept + $bill->companyaccept;
            $company->totalDiscount = $company->totalDiscount + $bill->networkname;
            $company->totalCarry = $company->totalCarry + $bill->customercarry;
            $company->totalNet = $company->totalNet + $bill->username;
            $i++;
        }

        $totalAccept = $totalAccept + $company->totalAccept;
        $totalDiscount = $totalDiscount + $company->totalDiscount;
        $totalCarry = $totalCarry + $company->totalCarry;
        $totalNet = $totalNet + $company->totalNet;

        array_push($result, $company);
    }

    $smarty->assign("totalAccept", $totalAccept);
    $smarty->assign("totalDiscount", $totalDiscount);
    $smarty->assign("totalCarry", $totalCarry);
    $smarty->assign("totalNet", $totalNet);
    $smarty->assign("companyClientsBills", $result);
    $smarty->assign("count", count($result));
}

function getDistinctCompanies($clientAreaId, $insuranceCompanyId, $branchId, $searchDateFrom) {
    global $billsEX;

    $branchQuery = '';
    $dateFromQuery = '';
    $clientAreaQuery = '';

    if ($branchId != -1) {
        $branchQuery = 'and b.branchid  =' . $branchId . ' ';
    }
    if ($searchDateFrom != '') {
        $dateFromQuery = 'and b.billdate like "' . $searchDateFrom . '-%"';
    }
    if ($clientAreaId != -1) {
        $clientAreaQuery = 'and c.clientareaid  =' . $clientAreaId . ' ';
    }


    $companys = $billsEX->getDistinctCompaniesWithBillsByInsuranceCompanyId($insuranceCompanyId, $branchQuery, $dateFromQuery, $clientAreaQuery);

    return $companys;
}

function getBillsInsCompany($insuranceCompanyId, $branchId, $searchDateFrom) {
    global $billsEX;
    global $insuranceCompanyDAO;
    global $smarty;

    $result = array();

    $totalAccept = 0;
    $totalDiscount = 0;
    $totalCarry = 0;
    $totalNet = 0;


    $branchQuery = '';
    $dateFromQuery = '';
    $insCompanyQuery = '';

    if ($insuranceCompanyId != -1) {
        $insCompanyQuery = 'and b.insurancecompanyid  =' . $insuranceCompanyId . ' ';
    }

    if ($branchId != -1) {
        $branchQuery = 'and b.branchid  =' . $branchId . ' ';
    }


    if ($searchDateFrom != '') {
        $dateFromQuery = 'and b.billdate like "' . $searchDateFrom . '-%"';
    }



    $insuranceCompanys = getDistinctInsCompanies($insCompanyQuery, $branchQuery, $dateFromQuery);
    foreach ($insuranceCompanys as $company) {
        $company->totalAccept = 0;
        $company->totalDiscount = 0;
        $company->totalCarry = 0;
        $company->totalNet = 0;


        $insuranceCompany = $insuranceCompanyDAO->load($company->insurancecompanyid);
        $company->companyname = $insuranceCompany->name;

        $companyClientsBills = $billsEX->getBillsByInsuranceCompanyId($company->insurancecompanyid, $branchQuery, $dateFromQuery, '');
        foreach ($companyClientsBills as $bill) {
            $bill->networkname = ($bill->companyaccept * ($bill->insdiscountpercent) / 100);  ##  insurance company discount value
            $bill->username = $bill->companyaccept - $bill->networkname - $bill->customercarry;    ## net required insurance from company

            $company->totalAccept = $company->totalAccept + $bill->companyaccept;
            $company->totalDiscount = $company->totalDiscount + $bill->networkname;
            $company->totalCarry = $company->totalCarry + $bill->customercarry;
            $company->totalNet = $company->totalNet + $bill->username;
            $i++;
        }

        $totalAccept = $totalAccept + $company->totalAccept;
        $totalDiscount = $totalDiscount + $company->totalDiscount;
        $totalCarry = $totalCarry + $company->totalCarry;
        $totalNet = $totalNet + $company->totalNet;

        array_push($result, $company);
    }

    $smarty->assign("totalAccept", $totalAccept);
    $smarty->assign("totalDiscount", $totalDiscount);
    $smarty->assign("totalCarry", $totalCarry);
    $smarty->assign("totalNet", $totalNet);
    $smarty->assign("companyClientsBills", $result);
    $smarty->assign("count", count($result));
}

function getDistinctInsCompanies($insCompanyQuery, $branchQuery, $dateFromQuery) {
    global $billsEX;

    $insCompanys = $billsEX->getDistinctInsCompaniesWithBills($insCompanyQuery, $branchQuery, $dateFromQuery);

    return $insCompanys;
}

?>