<?php
ob_start(); // start output buffering
header('Content-Type: application/json');
error_reporting(0);
ini_set('display_errors', 0);


include 'cors.php'; // Handles CORS preflight & headers
header('Content-Type: application/json');
include 'connection.php';
require 'vendor/autoload.php'; // Load Composer dependencies

use \Firebase\JWT\JWT;
use \Firebase\JWT\Key; 
use \Firebase\JWT\ExpiredException;

$config = include 'config.php';
$secret_key = $config['secret_key'];
$issuer = $config['issuer'];
$audience = $config['audience'];

// Check connection
if ($conn->connect_error) {
    echo json_encode(['success' => false, 'message' => 'Connection failed: ' . $conn->connect_error]);
    exit;
}

// Common JWT verification for both GET and POST
$headers = function_exists('apache_request_headers') ? apache_request_headers() : [];
if (!isset($headers['Authorization'])) {
    echo json_encode(["success" => false, "message" => "Authorization header missing"]);
    exit;
}

list($jwt) = sscanf($headers['Authorization'], 'Bearer %s');

try {
    // Decode JWT
    $decoded = JWT::decode($jwt, new Key($secret_key, 'HS256'));
    $company_id = $decoded->data->companyId;
    $uid = $decoded->data->uid;

    // ✅ Handle GET request - Fetch vouchers for this company
    if ($_SERVER['REQUEST_METHOD'] === 'GET') {
        $voucher_id = isset($_GET['voucher_number']) ? $_GET['voucher_id'] : null;

        if ($voucher_id) {
            // Fetch single voucher by voucher_id
            $query = "SELECT * FROM daily_entry WHERE com_id = ? AND voucher_number = ?";
            $stmt = $conn->prepare($query);
            $stmt->bind_param("is", $company_id, $voucher_id);
        } else {
            // Fetch all vouchers for the company
            $query = "SELECT * FROM daily_entry WHERE com_id = ? ORDER BY date DESC";
            $stmt = $conn->prepare($query);
            $stmt->bind_param("i", $company_id);
        }

        $stmt->execute();
        $result = $stmt->get_result();
        $data = [];

        while ($row = $result->fetch_assoc()) {
            $data[] = $row;
        }

        if (empty($data)) {
            echo json_encode(["success" => false, "message" => "No vouchers found"]);
        } else {
            echo json_encode(["success" => true, "data" => $data]);
        }

        $stmt->close();
        exit;
    }


    
   else if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    // Required fields for daily_entry
    $required_fields = ['purpose','voucher_id', 'advance_id', 'date','from_ledger','to_ledger','amount'];
    foreach ($required_fields as $field) {
        if (!isset($_POST[$field]) || trim($_POST[$field]) === '') {
            echo json_encode(["success" => false, "message" => "Required field missing: $field"]);
            exit;
        }
    }

    $purpose = $_POST['purpose'];                    // e.g. handover
    $voucher_id = $_POST['voucher_id'];
    $advance_id = $_POST['advance_id'];
    $date = $_POST['date'];
    $from_ledger = $_POST['from_ledger'];
    $to_ledger = $_POST['to_ledger'];
    $amount = floatval($_POST['amount']);
    $remark = $_POST['remark'] ?? '';

    $formatted_date = date('Y-m-d', strtotime($date));

    $conn->begin_transaction();

    // Check duplicate voucher in daily_entry
    $checkQuery = "SELECT COUNT(*) AS count 
                   FROM daily_entry 
                   WHERE voucher_id = ? AND com_id = ?";
    $stmtCheck = $conn->prepare($checkQuery);
    $stmtCheck->bind_param("si", $voucher_id, $company_id);
    $stmtCheck->execute();
    $checkRow = $stmtCheck->get_result()->fetch_assoc();
    $stmtCheck->close();

    if ($checkRow['count'] > 0) {
        $conn->rollback();
        echo json_encode(["success" => false, "message" => "Voucher ID already exists!"]);
        exit;
    }

    // Insert into daily_entry
    $insertQuery = "INSERT INTO daily_entry 
        (com_id, uid, purpose, voucher_id, date, from_ledger, to_ledger, advance_id,  amount, remark)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

    $stmt = $conn->prepare($insertQuery);
    $stmt->bind_param(
        "iissssssds",
        $company_id,
        $uid,
        $purpose,
        $voucher_id,
        $formatted_date,
        $from_ledger,
        $to_ledger,
        $advance_id,
        $amount,
        $remark
    );

    if (!$stmt->execute()) {
        $conn->rollback();
        echo json_encode([
            "success" => false,
            "message" => "Failed to insert daily entry",
            "error" => $stmt->error
        ]);
        exit;
    }
    $stmt->close();
    
    
    
        // Ledger entries
       // Ledger entries (unchanged)
$ledgerEntries = [
    ['ledger' => $from_ledger, 'particulars' => $to_ledger,   'credit' => $amount, 'debit' => 0.00],
    ['ledger' => $to_ledger,   'particulars' => $from_ledger, 'credit' => 0.00,   'debit' => $amount]
];

foreach ($ledgerEntries as $entry) {
    // Improved duplicate check: include debit and credit so two rows with same ledger but different dr/cr are allowed
    $checkLedger = "SELECT COUNT(*) AS count 
                    FROM ledger_day_wise 
                    WHERE voucher_number = ? AND ledger = ? AND com_id = ? AND debit = ? AND credit = ?";
    $stmtCheck = $conn->prepare($checkLedger);
    if (!$stmtCheck) {
        $conn->rollback();
        echo json_encode(["success" => false, "message" => "Prepare failed (checkLedger): " . $conn->error]);
        exit;
    }
    // types: voucher_number (s), ledger (s), com_id (i), debit (d), credit (d)
    $stmtCheck->bind_param("ssidd", $voucher_id, $entry['ledger'], $company_id, $entry['debit'], $entry['credit']);
    if (!$stmtCheck->execute()) {
        $stmtCheck->close();
        $conn->rollback();
        echo json_encode(["success" => false, "message" => "Execute failed (checkLedger): " . $stmtCheck->error]);
        exit;
    }
    $res = $stmtCheck->get_result()->fetch_assoc();
    $stmtCheck->close();

    if ($res['count'] == 0) {
        $insertLedger = "INSERT INTO ledger_day_wise 
            (com_id, uid, date, ledger, particulars, voucher_type, voucher_number, debit, credit)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
        $stmtLedger = $conn->prepare($insertLedger);
        if (!$stmtLedger) {
            $conn->rollback();
            echo json_encode(["success" => false, "message" => "Prepare failed (insertLedger): " . $conn->error]);
            exit;
        }
        // types: com_id (i), date (s), ledger (s), particulars (s), voucher_type (s), voucher_number (s), debit (d), credit (d)
        $stmtLedger->bind_param(
            "issssssdd",
            $company_id,
            $uid,
            $formatted_date,
            $entry['ledger'],
            $entry['particulars'],
            $purpose,
            $voucher_id,
            $entry['debit'],
            $entry['credit']
        );

        if (!$stmtLedger->execute()) {
            $stmtLedger->close();
            $conn->rollback();
            echo json_encode(["success" => false, "message" => "Failed to insert ledger entry", "error" => $stmtLedger->error]);
            exit;
        }
        $stmtLedger->close();
    } // end if count==0
}

    $conn->commit();

    echo json_encode(["success" => true, "message" => "Daily entry added successfully"]);
    exit;
}
     
     
     //daily entry fetch
     
    else if ($_SERVER['REQUEST_METHOD'] === 'GET') {
        $voucher_id = isset($_GET['voucher_id']) ? $_GET['voucher_id'] : null;

        if ($voucher_id) {
            // Fetch single voucher by voucher_id
            $query = "SELECT * FROM daily_entry WHERE com_id = ? AND voucher_id = ?";
            $stmt = $conn->prepare($query);
            $stmt->bind_param("is", $company_id, $voucher_id);
        } else {
            // Fetch all vouchers for the company
            $query = "SELECT * FROM daily_entry WHERE com_id = ? ORDER BY date DESC";
            $stmt = $conn->prepare($query);
            $stmt->bind_param("i", $company_id);
        }

        $stmt->execute();
        $result = $stmt->get_result();
        $data = [];

        while ($row = $result->fetch_assoc()) {
            $data[] = $row;
        }

        if (empty($data)) {
            echo json_encode(["success" => false, "message" => "No vouchers found"]);
        } else {
            echo json_encode(["success" => true, "data" => $data]);
        }

        $stmt->close();
        exit;
    }

    


// ✅ Voucher Edit
  

elseif ($_SERVER['REQUEST_METHOD'] === 'PUT') {
    $data = json_decode(file_get_contents("php://input"), true);
    $voucher_id = $data['voucher_id'] ?? 0;

    if (!$voucher_id) {
        ob_clean(); 
        echo json_encode(["success" => false, "message" => "Voucher ID required"]); 
        exit;
    }

    // ✅ Date formatting
    $formatted_date = null;
    if (!empty($data['date'])) {
        $timestamp = strtotime(str_replace('/', '-', $data['date']));
        if ($timestamp) {
            $formatted_date = date('Y-m-d', $timestamp);
        }
    }

    if (!$formatted_date) {
        ob_clean(); 
        echo json_encode(["success" => false, "message" => "Invalid date format"]); 
        exit;
    }

     $from_ledger = $data['from_ledger'];
    $to_ledger = $data['to_ledger'];
    $purpose = $data['purpose'];
    $amount = floatval($data['amount']);
    $advance_id =$data['advance_id'];
    

    $conn->begin_transaction();

    // ✅ Update voucher table
    $stmt = $conn->prepare("UPDATE daily_entry SET date = ?, `from_ledger` = ?, `to_ledger` = ?, purpose = ?, amount = ? , advance_id = ? WHERE voucher_id = ? AND com_id = ?");
    $stmt->bind_param("ssssdssi", $formatted_date, $from_ledger, $to_ledger, $purpose, $amount, $advance_id,  $voucher_id, $company_id);

    if (!$stmt->execute()) {
        $conn->rollback();
        ob_clean(); 
        echo json_encode(["success" => false, "message" => "Voucher update failed: ".$stmt->error]); 
        exit;
    }
    $stmt->close();

    // ✅ Update existing ledger entries only (no insert)
    $ledgerEntries = [
        ['ledger' => $from_ledger, 'particulars' => $to_ledger, 'credit' => $amount, 'debit' => 0.00],
        ['ledger' => $to_ledger, 'particulars' => $from_ledger, 'credit' => 0.00, 'debit' => $amount]
    ];

    foreach ($ledgerEntries as $entry) {
        $updateLedger = "UPDATE ledger_day_wise 
                         SET date = ?, particulars = ?, voucher_type = ?, debit = ?, credit = ?
                         WHERE voucher_number = ? AND ledger = ? AND com_id = ?";
        $stmtLedger = $conn->prepare($updateLedger);
        $stmtLedger->bind_param(
            "sssddssi",
            $formatted_date,
            $entry['particulars'],
            $purpose,
            $entry['debit'],
            $entry['credit'],
            $voucher_id,
            $entry['ledger'],
            $company_id
        );

        if (!$stmtLedger->execute()) {
            $conn->rollback();
            ob_clean();
            echo json_encode(["success" => false, "message" => "Ledger update failed", "error" => $stmtLedger->error]);
            exit;
        }
        $stmtLedger->close();
    }

    // ✅ Commit all updates
    $conn->commit();
    ob_clean();
    echo json_encode(["success" => true, "message" => "Voucher and ledger entries updated successfully"]);
    exit;
}




    
     // ✅ DELETE: Remove deposit + ledger






elseif ($_SERVER['REQUEST_METHOD'] === 'DELETE') {
    $data = json_decode(file_get_contents("php://input"), true);
    $voucher_no = $data['voucher_id'] ?? '';

    if (empty($voucher_no)) {
        echo json_encode(["success" => false, "message" => "Voucher ID required"]);
        exit;
    }

    // Start transaction for safe delete
    $conn->begin_transaction();

    try {
        // Delete from daily_entry
        $stmt1 = $conn->prepare("DELETE FROM daily_entry WHERE voucher_id=? AND com_id=?");
        $stmt1->bind_param("si", $voucher_no, $company_id);
        $stmt1->execute();

        // Delete from ledger_day_wise
        $stmt2 = $conn->prepare("DELETE FROM ledger_day_wise WHERE voucher_number=? AND com_id=?");
        $stmt2->bind_param("si", $voucher_no, $company_id);
        $stmt2->execute();

        if ($stmt1->affected_rows > 0 || $stmt2->affected_rows > 0) {
            $conn->commit();
            echo json_encode(["success" => true, "message" => "Voucher deleted from both tables"]);
        } else {
            $conn->rollback();
            echo json_encode(["success" => false, "message" => "No matching voucher found"]);
        }

        $stmt1->close();
        $stmt2->close();

    } catch (Exception $e) {
        $conn->rollback();
        echo json_encode(["success" => false, "message" => "Delete failed"]);
    }

    exit;
}


    
    



    // Invalid Method
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);

} catch (ExpiredException $e) {
    echo json_encode(["success" => false, "message" => "Token has expired"]);
} catch (Exception $e) {
    echo json_encode(["success" => false, "message" => "Error: " . $e->getMessage()]);
}

$conn->close();
?>
