<?php
require "showshp.php";
session_start();
if(!isset($_SESSION['titles']) || !isset($_SESSION['positions'])|| !isset($_SESSION['usernames'])){
header("location:index.php");
}


$conn=mysqli_connect("localhost","primarysales","S5L7lF01EQZvQrGK","primarysales_dianaold");

$actp=$_REQUEST['actp'];

if($actp=='mradds' || $actp=='mredits'){

$agents=$_REQUEST['magents'];
$dates=$_REQUEST['mdates'];
$discounts=$_REQUEST['mdiscounts'];
$areas=$_REQUEST['areas'];
$mcn=$_REQUEST['mcn'];

if($actp=='mradds'){
$sqlst="select max(mr_numbers) from market_returns ";
$qry=mysqli_query($conn,$sqlst);
$rst=mysqli_fetch_row($qry);

if(mysqli_num_rows($qry)==0){
$mrnumbers=date('Y')."0001";}
else{
if(intval($rst[0],10)==0){
$mrnumbers=date('y')."0001";}
else{
$mrnumbers=intval($rst[0],10)+1;}
}
}
else{
$sqlst="delete from market_returns where mr_numbers='".$_REQUEST['mrnumbers']."' ";
$qry=mysqli_query($conn,$sqlst);
$mrnumbers=$_REQUEST['mrnumbers'];
}


$sqlst="select distinct zone_order,zone,rsm_name,executive_name,agent_type,territory_name,region,chanelname,agent_name from agentsmrd where agent_name='".$agents."' ";
$qry=mysqli_query($conn,$sqlst);
$rst=mysqli_fetch_row($qry);

$zoneorders=$rst[0];
$zones=$rst[1];
$rsmnames=$rst[2];
$executives=$rst[3];
$agenttypes=$rst[4];
$territorys=$rst[5];
$regions=$rst[6];
$chnl=$rst[7];
$agnm=$rst[8];


for($cnt=1;$cnt<$mcn;$cnt++){

$sqlst="select distinct main_reason,sub_reason from mreasons where sub_reason='".$_REQUEST['mreasons'.$cnt]."' ";

$qry=mysqli_query($conn,$sqlst);
$rst=mysqli_fetch_row($qry);

$reasons=$rst[0];
$mrtypes=$rst[1];

$sqlst="select distinct item_ranges, sub_ranges,packets_per_box,packet_weight,item_name from itemsmrd where item_name_mrt='".$_REQUEST['items'.$cnt]."' ";
$qry=mysqli_query($conn,$sqlst);
$rst=mysqli_fetch_row($qry);

$sqlst="insert into market_returns (dates,mr_numbers,zone_orders,zones,regions,chanell,rsm_names,agent_names,agent_types,territory_names,areas,item_names,pcs_price,pcs_qty,reasons,mr_types,actions,discount_rates,item_ranges,sub_ranges,packets_per_box,packet_weights,user_names,user_dates) values ('".$_REQUEST['mdates']."','".$mrnumbers."',".$zoneorders.
",'".$zones."','".$regions."','".$chnl."','".$rsmnames."','".$agnm."','".$agenttypes."','".$territorys."','".$areas."','".$rst[4]."',".$_REQUEST['prices'.$cnt].",".
$_REQUEST['qtys'.$cnt].",'".$reasons."','".$mrtypes."','".$_REQUEST['mactions'.$cnt]."',".$discounts.",'".$rst[0]."','".$rst[1]."',".$rst[2].",".$rst[3].",'".$_SESSION['usernames']."',now())";


if(($qry=mysqli_query($conn,$sqlst))==false){
echo "errors";}
else{
echo "oks<td>".$mrnumbers."<td>".$_REQUEST['mdates']."<td>";}
}

}

