<?php
session_start();
include('../include/connection.php');
include('../include/app_config.php');
include('../lib/app_stat.php');
require_once '../lib/dbconfig.php';

if(isset($_POST['insert']))
{
    switch ($_POST['insert'])
    {
        case 'disco_setup':
            $status="no";
            $success = 0;
            if(isset($_POST['status']))
            {
                $status="yes";
            }
            if($_POST['name'] != "")
            {
                $sql="insert into discos (name,state_id,is_active,date_created) values (:name,:state,:status,:date)";
                $fields=array(':name'=>ucwords($_POST['name']), ':state'=>$_POST['state'], ':status'=>$status,':date'=>date('d-m-Y'));
                $q=$con->insert_query($sql,$fields);
                if($q)
                {
                    $discoid = $con->lastID;
                    $state = explode(',', $_POST['franchiselist']);
                    foreach($state as $st)
                    {
                        $sql = "insert into disco_state (state_id,disco_id) values (:state,:disco)";
                        $con->insert_query($sql,array(':state'=>$st,':disco'=>$discoid));
                    }
                    $success = 1;  //success
                }
            }
            else
            {
                $success = 3;  //empty required fields
            }
            echo json_encode(array('success'=>$success));
            break;
            
        case 'user_setup':
            $status=0;
            $success = 0;
            $msg = "";
            if(isset($_POST['status']))
            {
                $status=1;
            }
            $sql = "select id from users where email=:email";
            $q=$con->select_query($sql,array(':email'=>$_POST['email']));
            if(count($q) > 0)
            {
                $success = 2;  //code exist
                echo json_encode(array('success'=>$success));
                return;
            }
            
            if($_POST['email'] != "" && $_POST['password'] != "" && $_POST['repassword'] != "")
            {
                $reg = $user->register($_POST['email'], $_POST['password'], $_POST['repassword'], $status, $_POST['role'], "", "");
                if($reg)
                {
                    $success = 1;  //success
                    
                    //save dico_admin, if disco
                    if($_POST['role'] == DISCO_USER_KEY)
                    {
                        $user_id = $user->lastuser;
                        $con->delete_query("delete from disco_admin where user_id=:user",array(':user'=>$user_id));
                        $sql = "insert into disco_admin (user_id,disco_id,date_created) values (:user,:disco,:date)";
                        $fields = array(
                            ':user'=>$user_id,
                            ':disco'=>$_POST['disco'],
                            ':date'=>date('d-m-Y H:i A')
                        );
                        $con->insert_query($sql,$fields);
                    }
                }
                else 
                {
                    foreach($user->errormsg as $error)
                     {
                         $msg .=$error.'.';
                     }
                    $success = 4;
                }
            }
            else
            {
                $success = 3;  //empty required fields
            }
            echo json_encode(array('success'=>$success,'msg'=>$msg));
            break;
        
        case 'article_setup':
            $file_error = 0;
            $success = 0;
            if(isset($_FILES['photo']) && !empty($_FILES['photo']))
            {
                $isvalidsize = filesize($_FILES['photo']['tmp_name']) <= MAX_FILE_SIZE;
                if(!$isvalidsize)
                {
                    $file_error = 3;
                    echo json_encode(array('success'=>$success,'file_error'=>$file_error));
                    return;
                }
            }
            if(!empty($_POST['title']) && !empty($_POST['body']) && !empty($_POST['category']))
            {
                $status = 0;
                if(isset($_POST['status']))
                {
                    $status=1;
                }
                $sql = "insert into news (title,date_created,category_id,body,is_published,author) values
                                (:title,:date,:cat,:body,:status,:author)";
                $fields = array(
                    ':title'=>$_POST['title'],
                    ':date'=>$_POST['date_created'],
                    ':cat'=>$_POST['category'],
                    ':body'=>$_POST['body'],
                    ':status'=>$status,
                    ':author'=>$_POST['author']
                );
                $q=$con->insert_query($sql,$fields);
                if($q)
                {
                    $success = 1;
                    $articleid = $con->lastID;
                    if(isset($_FILES['photo']) && !empty($_FILES['photo']))
                    {
                        $ext=pathinfo($_FILES['photo']['name'], PATHINFO_EXTENSION);
                        if(strcasecmp($ext, "jpeg") == 0 || strcasecmp($ext, "jpg") == 0 || strcasecmp($ext, "png") == 0 || strcasecmp($ext, "pdf") == 0)
                        {
                            $photo = "article".$articleid.'.'.$ext;
                            move_uploaded_file($_FILES['photo']['tmp_name'], UPLOADS_FOLDER.$photo);
                            $sql = "update news set featured_image=:img where id=:id";
                            $con->update_query($sql,array(':img'=>$photo,':id'=>$articleid));
                        }
                        else
                        {
                            $file_error = 1;
                        }
                    }
                    else
                    {
                        $file_error = 2;
                    }
                }
            }
            else 
            {
                $success = 3;
            }
            echo json_encode(array('success'=>$success,'file_error'=>$file_error));
            break;
            
        case 'daily_energy_watch':
            $success = 0;
            if(empty($_POST['fromdate']) || empty($_POST['todate']))
            {
                $success = 3;
                echo json_encode(array('success'=>$success));
                return;
            }
            if(!empty($_POST['batchid']))
            {
                $sql = "delete from daily_energy_watch where batchid=:id";
                $con->delete_query($sql,array(':id'=>$_POST['batchid']));
            }
            $i = 0;
            $insert_count = 0;
            $batchid = 0;
            foreach($_POST['fieldname'] as $field)
            {
                if(!empty($field))
                {
                    $status = 0;
                    if(isset($_POST['status'.$i]))
                    {
                        $status = 1;
                    }
                    $sql = "insert into daily_energy_watch (fromdate,todate,fromvalue,tovalue,fieldname,status,batchid) 
                        values (:from,:to,:fromval,:toval,:field,:status,:batchid)";
                    $fields = array(
                        ':from'=>$_POST['fromdate'],
                        ':to'=>$_POST['todate'],
                        ':fromval'=>$_POST['fromvalue'][$i],
                        ':toval'=>$_POST['tovalue'][$i],
                        ':field'=>$field,
                        ':status'=>$status,
                        ':batchid'=>$batchid
                    );
                    $q=$con->insert_query($sql,$fields);
                    if($q)
                    {
                        if($i == 0)
                        {
                            $batchid = $con->lastID;
                            $sql = "update daily_energy_watch set batchid=:id where id=:id";
                            $con->update_query($sql,array(':id'=>$batchid));
                            $_SESSION['batchid'] = $batchid;
                        }
                        $insert_count += 1;
                    }
                }
                $i++;
            }
            if($insert_count > 0)
            {
                $success = 1;
            }
            echo json_encode(array('success'=>$success));
            break;
            
        case 'category_setup':
            $status=0;
            $success = 0;
            if(isset($_POST['status']))
            {
                $status=1;
            }
            $sql = "select * from news_category where code=:code";
            $q=$con->select_query($sql,array(':code'=>$_POST['code']));
            if(count($q) > 0)
            {
                $success = 2;  //code exist
                echo json_encode(array('success'=>$success));
                return;
            }
            
            if($_POST['code'] != "" && $_POST['name'] != "")
            {
                $sql="insert into news_category (code,name,status) values (:code,:name,:status)";
                $fields=array(':code'=>$_POST['code'], ':name'=>ucwords($_POST['name']), ':status'=>$status);
                $q=$con->insert_query($sql,$fields);
                if($q)
                {
                    $success = 1;  //success
                }
            }
            else
            {
                $success = 3;  //empty required fields
            }
            echo json_encode(array('success'=>$success));
            break;
            
            case 'complaint_category_setup':
                $status=0;
                $success = 0;
                if(isset($_POST['status']))
                {
                    $status=1;
                }
                
                if($_POST['name'] != "")
                {
                    $sql="insert into complaint_category (name,is_active) values (:name,:status)";
                    $fields=array(':name'=>ucwords($_POST['name']), ':status'=>$status);
                    $q=$con->insert_query($sql,$fields);
                    if($q)
                    {
                        $success = 1;  //success
                    }
                }
                else
                {
                    $success = 3;  //empty required fields
                }
                echo json_encode(array('success'=>$success));
                break;
                
            case 'announcement_setup':
                if(!empty($_POST['body']) && !empty($_POST['title']))
                {
                    $status=0;
                    $success = 0;
                    if(isset($_POST['status']))
                    {
                        $status=1;
                    }
                    $sender = "";
                    if($_SESSION['user_role'] == IWIN_USER_KEY || $_SESSION['user_role'] == SUPER_ADMIN_USER_KEY)
                    {
                        $sender = "IWIN";
                    }
                    else if($_SESSION['user_role'] == NERC_USER_KEY)
                    {
                        $sender = "NERC";
                    }
                    else if($_SESSION['user_role'] == DISCO_USER_KEY)
                    {
                        $sender = GetDiscoName($_POST['disco'], $con);
                    }
                    $sql = "insert into announcement (title,type,body,date_created,is_published,state_id,lga_id,disco_id,sender) values
                                (:title,:type,:body,:date,:status,:state,:lga,:disco,:sender)";
                    $fields = array(
                        ':title'=>$_POST['title'],
                        ':type'=>$_POST['type'],
                        ':body'=>$_POST['body'],
                        ':date'=>date('d-m-Y H:i'),
                        ':status'=>$status,
                        ':state'=>$_POST['state'],
                        ':lga'=>$_POST['lga'],
                        ':disco'=>$_POST['disco'],
                        ':sender'=>$sender
                    );
                    $q=$con->insert_query($sql,$fields);
                    if($q)
                    {
                        $success = 1;
                    }
                }
                else
                {
                    $success = 3;  //empty required fields
                }
                echo json_encode(array('success'=>$success));
                break;
                
            case 'power_supply':
                $success = 0;
                if(empty($_POST['date']))
                {
                    $success = 3;
                    echo json_encode(array('success'=>$success));
                    return;
                }
                if(!empty($_POST['batchid']))
                {
                    $sql = "delete from stats where batch_id=:id OR date_created = :date";
                    $con->delete_query($sql,array(':id'=>$_POST['batchid'], ':date'=>$_POST['date']));
                }
                $i = 0;
                $insert_count = 0;
                $batchid = 0;
                foreach($_POST['location'] as $loc)
                {
                    if(!empty($loc))
                    {
                        $sql = "insert into stats (location,generation,date_created,batch_id)
                        values (:loc,:gen,:date,:batch)";
                        $fields = array(
                            ':loc'=>$loc,
                            ':gen'=>$_POST['gen'][$i],
                            ':date'=>$_POST['date'],
                            ':batch'=>$batchid
                        );
                        $q=$con->insert_query($sql,$fields);
                        if($q)
                        {
                            if($i == 0)
                            {
                                $batchid = $con->lastID;
                                $sql = "update stats set batch_id=:id where id=:id";
                                $con->update_query($sql,array(':id'=>$batchid));
                                $_SESSION['batchid'] = $batchid;
                            }
                            $insert_count += 1;
                        }
                    }
                    $i++;
                }
                if($insert_count > 0)
                {
                    $success = 1;
                }
                echo json_encode(array('success'=>$success));
                break;
                
                case 'generation_stats':
                    $success = 0;
                    if(!empty($_POST['date']) && (!empty($_POST['peak_gen']) || !empty($_POST['energy'])))
                    {
                        $sql = "insert into stats (date_created,peak_gen,energy) values (:date,:peak,:energy)";
                        $fields = array(
                            ':date'=>$_POST['date'],
                            ':peak'=>$_POST['peak_gen'],
                            ':energy'=>$_POST['energy']
                        );
                        $q=$con->insert_query($sql,$fields);
                        if($q)
                        {
                            $success = 1;
                        }
                    }
                    else
                    {
                        $success = 3;  //empty required fields
                    }
                    echo json_encode(array('success'=>$success));
                    break;
                    
                case 'event_setup':
                    $success = 0;
                    $status = 0;
                    $id = 0;
                    if(isset($_POST['status']))
                    {
                        $status = 1;
                    }
                    if(!empty($_POST['event_date']) && (!empty($_POST['title']) || !empty($_POST['body'])))
                    {
                        $sql = "insert into event (event_date,title,description,status) values (:date,:title,:desc,:status)";
                        $fields = array(
                            ':date'=>$_POST['event_date'],
                            ':title'=>$_POST['title'],
                            ':desc'=>$_POST['body'],
                            ':status'=>$status
                        );
                        $q=$con->insert_query($sql,$fields);
                        if($q)
                        {
                            $success = 1;
                            $id = $con->lastID;
                        }
                    }
                    else
                    {
                        $success = 3;  //empty required fields
                    }
                    echo json_encode(array('success'=>$success,'id'=>$id));
                    break;
                    
                case 'event_photos':
                    $success = 0;
                    $file_error = 0;
                    $success = 0;
                    if(isset($_FILES['photo']) && !empty($_FILES['photo']))
                    {
                        $isvalidsize = filesize($_FILES['photo']['tmp_name']) <= MAX_FILE_SIZE;
                        if(!$isvalidsize)
                        {
                            $file_error = 3;
                            echo json_encode(array('success'=>$success,'file_error'=>$file_error));
                            return;
                        }
                        
                        $ext = strtolower(pathinfo($_FILES['photo']['name'], PATHINFO_EXTENSION));
                        if (in_array($ext, ["jpeg", "jpg", "png", "pdf"])) {
                            $filename = pathinfo($_FILES['photo']['name'], PATHINFO_FILENAME);
                            $filename = str_replace(' ', '-', $filename);
                            $filename = str_replace(['@','.','[',']','_','#','$', ',','(',')'], '', $filename);

                            $photo = $filename . $_POST['eventid'] . '.' . $ext;

                            move_uploaded_file($_FILES['photo']['tmp_name'], UPLOADS_FOLDER . $photo);
                            $sql = "insert into eventphoto (eventid,photo) values (:eventid,:photo)";
                            $con->insert_query($sql,array(':eventid'=>$_POST['eventid'],':photo'=>$photo));
                        }
                        else
                        {
                            $file_error = 1;
                        }
                    }
                    echo json_encode(array('success'=>$success,'file_error'=>$file_error));
                    break;
                    
                case 'staff_birthday_setup':
                    $success = 0;
                    if(!empty($_POST['firstname']) && (!empty($_POST['lastname']) || !empty($_POST['dob'])  || !empty($_POST['email'])))
                    {
                        $sql = "insert into staff (firstname,lastname,othernames,dob,position,dept,date_created,email) 
                                values (:firstname,:lastname,:onames,:dob,:position,:dept,:date,:email)";
                        $fields = array(
                            ':firstname'=>$_POST['firstname'],
                            ':lastname'=>$_POST['lastname'],
                            ':onames'=>$_POST['othernames'],
                            ':dob'=>$_POST['dob'],
                            ':position'=>$_POST['pos'],
                            ':dept'=>$_POST['dept'],
                            ':date'=>date('d-m-Y h:i A'),
                            ':email'=>$_POST['email']
                        );
                        $q=$con->insert_query($sql,$fields);
                        if($q)
                        {
                            $success = 1;
                        }
                    }
                    else
                    {
                        $success = 3;  //empty required fields
                    }
                    echo json_encode(array('success'=>$success));
                    break;
                    
                case 'admin_setup':
                    $success = 0;
                    $error = [];
                    if(!empty($_POST['firstname']) && !empty($_POST['lastname']) && !empty($_POST['email'])  && !empty($_POST['password']))
                    {
                        $umail = $_POST['email'];
                        $upass = $_POST['password'];
                        $repeatpass = $_POST['r_password'];
                        $status = 1;
                        $role = "admin";
                        $firstname = $_POST['firstname'];
                        $lastname = $_POST['lastname'];

                        // register the user
                        if($user->register($umail,$upass,$repeatpass,$status,$role,$firstname,$lastname))
                        {
                            $success = 1;
                        } else
                        {
                            $success = 2; // error
                            $error[] = $user->errormsg; // the returned error
                        } 
                    }
                    else
                    {
                        $success = 3;  //empty required fields
                    }
                    echo json_encode(array('success'=>$success, 'error'=>$error));
                    break;


    }
}
?>