<?php

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");
header("Content-Type: application/json");

$method = $_SERVER['REQUEST_METHOD'];
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    http_response_code(204);
    exit();
}

require 'db.php';
require 'helper.php';
switch($method) {
    case 'POST':
        $input = json_decode(file_get_contents("php://input"), true);
        
        if ($_GET['action'] == 'register') {
            register($input);
        } else if ($_GET['action'] == 'login') {
            login($input);
        } else if ($_GET['action'] == 'detail') {
            userdetail($input);
        }
        break;
    default:
        echo json_encode(['message' => 'Method not allowed']);
        break;
}

function register($data) {
    global $conn;
    
    $username = $data['username'];
    $password = password_hash($data['password'], PASSWORD_BCRYPT);
    
    $stmt = $conn->prepare("INSERT INTO users (username, password) VALUES (:username, :password)");
    $stmt->bindParam(':username', $username);
    $stmt->bindParam(':password', $password);
    
    if ($stmt->execute()) {
        echo json_encode(['message' => 'User registered successfully']);
    } else {
        echo json_encode(['message' => 'Registration failed']);
    }
}

function login($data) {
    global $conn;
    
    $username = $data['username'];
    $password = $data['password'];
    
    $stmt = $conn->prepare("SELECT * FROM users WHERE username = :username");
    $stmt->bindParam(':username', $username);
    $stmt->execute();
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($user && password_verify($password, $user['password'])) {
        $token = generateToken();
        
        $stmt = $conn->prepare("UPDATE users SET token = :token WHERE id = :id");
        $stmt->bindParam(':token', $token);
        $stmt->bindParam(':id', $user['id']);
        $stmt->execute();
        
            $stmts = $conn->prepare("SELECT * FROM Usermapping WHERE StaffID = :username");
                $stmts->bindParam(':username', $username);
                $stmts->execute();
                $users = $stmts->fetch(PDO::FETCH_ASSOC); 
    
                $stmtr = $conn->prepare("UPDATE Usermapping SET token = :token WHERE StaffID = :id");
                $stmtr->bindParam(':token', $token);
                $stmtr->bindParam(':id', $users['StaffID']);
                $stmtr->execute();
                
                
                
                
                
                $username = $token;
    

    $stmt = $conn->prepare("SELECT * FROM users WHERE token = :username");
    $stmt->bindParam(':username', $username);
    $stmt->execute();
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($user && ($username == $user['token'])) {
    $userid = $user['username'];
    $stmt = $conn->prepare("SELECT * FROM Usermapping WHERE StaffID = :username");
    $stmt->bindParam(':username', $userid);
    $stmt->execute();
    $users = $stmt->fetch(PDO::FETCH_NUM);
    
    //if ($user && ($username == $user[1])) {
        

                              for($i=0;$i<count($users);$i++){
                                   ${'data'.$i}=$users[$i];
                                  $output[]=${'data'.$i};
                              }
                            
                          
         echo json_encode(['token' => $output]);
         
         
        //echo json_encode(['token' => $token]);
    } else {
        echo json_encode(['message' => 'Login failed']);
    }
}
}
function userdetail($data) {
    global $conn;
    
     $username = $data['username'];
    

    $stmt = $conn->prepare("SELECT * FROM users WHERE token = :username");
    $stmt->bindParam(':username', $username);
    $stmt->execute();
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($user && ($username == $user['token'])) {
    $userid = $user['username'];
    $stmt = $conn->prepare("SELECT * FROM Usermapping WHERE StaffID = :username");
    $stmt->bindParam(':username', $userid);
    $stmt->execute();
    $users = $stmt->fetch(PDO::FETCH_NUM);
    
    //if ($user && ($username == $user[1])) {
        

                              for($i=0;$i<count($users);$i++){
                                   ${'data'.$i}=$users[$i];
                                  $output[]=${'data'.$i};
                              }
                            
                          
         echo json_encode(['token' => $output]);

    }else {
        echo json_encode(['message' => 'Login failed']);
    }
}


    
function addexpense($data) {
    global $conn;
    
   // $username = $data['username'];
   
            $requestID=$data[''];
            $miscode=$data[''];
            $branchCode=$data[''];
            $itemName=$data[''];
            $itemCode=$data[''];
            $quantity=$data[''];
            $amount=$data[''];
            $currencyCode=$data[''];
            $currencyRate=$data[''];
            $lcyAmount=$data[''];
            $narration=$data[''];
            $initiationDate=$data[''];
            $initiatorId=$data[''];
            $vat=$data[''];
            $percentageAmount=$data[''];
            $transId=$data[''];
            
    $stmt = $conn->prepare("INSERT INTO users 
    (RequestID, Miscode, BranchCode, ItemName, ItemCode, Quantity, Amount, CurrencyCode, CurrencyRate, LCYAmount, Narration, InitiationDate, InitiatorId, VAT, PercentageAmount, TransId) 
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");

                $stmt->bindParam(1, $requestID);
                $stmt->bindParam(2, $miscode);
                $stmt->bindParam(3, $branchCode);
                $stmt->bindParam(4, $itemName);
                $stmt->bindParam(5, $itemCode);
                $stmt->bindParam(6, $quantity);
                $stmt->bindParam(7, $amount);
                $stmt->bindParam(8, $currencyCode);
                $stmt->bindParam(9, $currencyRate);
                $stmt->bindParam(10, $lcyAmount);
                $stmt->bindParam(11, $narration);
                $stmt->bindParam(12, $initiationDate);
                $stmt->bindParam(13, $initiatorId);
                $stmt->bindParam(14, $vat);
                $stmt->bindParam(15, $percentageAmount);
                $stmt->bindParam(16, $transId);

// Execute the statement

    if ($stmt->execute()) {
        echo json_encode(['message' => 'Expense added successfully']);
    } else {
        echo json_encode(['message' => 'Expense failed']);
    }
}
?>
