<?php


session_start();
if($_SESSION['dbName']==""){
    header("location:../index.php");
}

include("config.inc.php");

$connection = mysql_connect($config['dbServer'],$config['dbUser'],$config['dbPass']) or die("Could not connect to DB");
mysql_select_db($_SESSION['dbName'],$connection) or die("Could not find DB");

$selectedLegalType = $_POST['legaltype'];
$selectedLegalTypedesc = $_POST['legaltypedesc'];
$mainmode = $_POST['mainmode'];

if($mainmode == ''){header("Location: Form_LegalType.php");}
else if($mainmode == 'edit') {
    $legaltypequery = "update clientslegaltype set clientlegaltype_description = '$selectedLegalTypedesc'
        where clientslegaltype_code = '$selectedLegalType'";
    mysql_query($legaltypequery, $connection) or die(mysql_error());

    header('Location: Form_LegalType.php?selectedlegaltype=' . $selectedLegalType . '&selectedlegaltypedesc=' . $selectedLegalTypedesc);
}
else if($mainmode == 'add'){
    $legaltypequery = "select * from clientslegaltype where clientslegaltype_code = '$selectedLegalType'";
    $result = mysql_query($legaltypequery, $connection);
    if(mysql_num_rows($result) > 0){
        while($row = mysql_fetch_row($result)){
            $selectedLegalTypedesc = $row[2];
        }
        header('Location: Form_LegalType.php?message=Legal type already available, please edit&selectedlegaltype=' . $selectedLegalType . '&selectedlegaltypedesc=' . $selectedLegalTypedesc . '&mainmode="edit"');
    }
    else {
        $legaltypequery = "insert into clientslegaltype (clientslegaltype_code,clientlegaltype_description) VALUES ('$selectedLegalType','$selectedLegalTypedesc')";
        mysql_query($legaltypequery, $connection) or die(mysql_error());

        header('Location: Form_LegalType.php?selectedlegaltype=' . $selectedLegalType . '&selectedlegaltypedesc=' . $selectedLegalTypedesc);
    }
}
else if($mainmode == 'delete'){
    $legaltypequery = "select Client_CompLegalType from clients where Client_CompLegalType = '$selectedLegalType'";
    $result = mysql_query($legaltypequery, $connection);
    if(mysql_num_rows($result) > 0){
        header('Location: Form_LegalType.php?message=Cannot delete record.');
    }else {
        $legaltypequery = "delete from clientslegaltype where clientslegaltype_code = '$selectedLegalType'";
        mysql_query($legaltypequery, $connection) or die(mysql_error());
        header('Location: Form_LegalType.php');
    }
}

//clientslegaltype_id, clientslegaltype_code, clientlegaltype_description