<?php
session_start();
require_once "config.php";

// Function to sanitize input
function sanitizeInput($input) {
    return htmlspecialchars(strip_tags(trim($input)));
}

function handleFileUpload($file) {
    $target_dir = "assets/images/clients/"; // Specify your upload directory
    $timestamp = time();
    $unique_filename = $timestamp;
    $target_file = $target_dir . $unique_filename;
    $uploadOk = 1;
    $fileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));

    // Check if file size is within limit
    if ($file["size"] > 500000) { // Limit file size to 500KB
        echo "Sorry, your file is too large.";
        $uploadOk = 0;
    }

    // Check if $uploadOk is set to 0 by an error
    if ($uploadOk == 0) {
        echo "Sorry, your file was not uploaded.";
        return false;
    // If everything is ok, try to upload file
    } else {
        if (move_uploaded_file($file["tmp_name"], $target_file)) {
            return $unique_filename; // Return the unique filename
        } else {
            echo "Sorry, there was an error uploading your file.";
            return false;
        }
    }
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    
    $compname = sanitizeInput($_POST['Compname']);
    $compnum = sanitizeInput($_POST['Compnumber']);
    $gst == sanitizeInput($_POST['gst']);
    $client_name = sanitizeInput($_POST['client_name']);
    $phone = sanitizeInput($_POST['phone']);
    $email = sanitizeInput($_POST['email']);
    $designation = sanitizeInput($_POST['designation']);
    $website = sanitizeInput($_POST['website']);
    $client_type = sanitizeInput($_POST['client_type']);
    $address = sanitizeInput($_POST['address']);
    $remarks = sanitizeInput($_POST['remarks']);
    $status = sanitizeInput($_POST['status']);
    $assigned_to = sanitizeInput($_POST['assigned_to']);
    $date = date("Y-m-d H:i:s");

   // Handle file upload if a file was uploaded
    $documents = sanitizeInput($_POST['current_documents']);
    if (isset($_FILES['documents']) && $_FILES['documents']['error'] == 0) {
        $uploaded_file = handleFileUpload($_FILES['documents']);
        if ($uploaded_file === false) {
            die("Error uploading file");
        } else {
            $documents = $uploaded_file;
        }
    }

    if (isset($_GET['action'])) {
        $action = $_GET['action'];

        if ($action == 'add') {
            $sql = "INSERT INTO clients (compname,compnum,gst,name, phone, email, website, designation, documents, type, address, remarks, status, assigned_to, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

            if ($stmt = mysqli_prepare($conn, $sql)) {
                mysqli_stmt_bind_param($stmt, "sssssssssssss", $compname, $compnum, $gst, $client_name, $phone, $email, $website, $designation, $documents, $client_type, $address, $remarks, $status, $assigned_to, $date, $date);

                if (mysqli_stmt_execute($stmt)) {
                    mysqli_stmt_close($stmt);
                    mysqli_close($conn);
                    $_SESSION['success_message'] = "Client added successfully.";
                    header("location: client.php");
                    exit();
                } else {
                    echo "Error: " . mysqli_error($conn);
                }
            } else {
                echo "Error: " . mysqli_error($conn);
            }
        }

        if ($action == 'edit') {
            $client_id = sanitizeInput($_POST['client_id']);
            $sql = "UPDATE clients SET compname=?,compnum=?,gst=?,name=?, phone=?, email=?, website=?, designation=?, documents=?, type=?, address=?, remarks=?, status=?, assigned_to=?, updated_at=? WHERE id=?";

            if ($stmt = mysqli_prepare($conn, $sql)) {
                mysqli_stmt_bind_param($stmt, "ssssssssssssi", $compname, $compnum, $gst,$client_name, $phone, $email, $website,  $designation, $documents, $client_type, $address, $remarks, $status, $assigned_to, $date, $client_id);

                if (mysqli_stmt_execute($stmt)) {
                    mysqli_stmt_close($stmt);
                    mysqli_close($conn);
                    $_SESSION['success_message'] = "Client updated successfully.";
                    header("location: client.php");
                    exit();
                } else {
                    echo "Error: " . mysqli_error($conn);
                }
            } else {
                echo "Error: " . mysqli_error($conn);
            }
        }

        if ($action == 'delete') {
            $client_id = sanitizeInput($_POST['client_id']);
            $sql = "DELETE FROM clients WHERE id=?";

            if ($stmt = mysqli_prepare($conn, $sql)) {
                mysqli_stmt_bind_param($stmt, "i", $client_id);

                if (mysqli_stmt_execute($stmt)) {
                    mysqli_stmt_close($stmt);
                    mysqli_close($conn);
                    $_SESSION['success_message'] = "Client deleted successfully.";
                    header("location: client.php");
                    exit();
                } else {
                    echo "Error: " . mysqli_error($conn);
                }
            }
        }
    }
}
?>
