<?php
session_start();
ini_set('session.cookie_secure', 1);
require_once "../../includes/db.php";
header('Content-Type: application/json');

$comp_id = isset($_GET['comp_id']) ? (int)$_GET['comp_id'] : 0;
$uid  =$_SESSION['user_id'];

session_write_close();

        $loc_id = isset($_POST['loc_id']) ? intval($_POST['loc_id']) : 0;
        $ord_no = isset($_POST['ord_no']) ? intval($_POST['ord_no']) : 0;
        $t_type = isset($_POST['t_type']) ? trim($_POST['t_type']) : '';
        $confby = isset($_POST['confby']) ? trim($_POST['confby']) : '';
        
        
if ($t_type === 'DEL' || $t_type === 'GR') {
    
    $stmt = $pdo->prepare("
    UPDATE transactions SET t_status='Confirmed', t_conf_by= :uid, t_conf_date=Now() WHERE co_id= :loc_id AND t_doc_no= :ord_no AND t_type= :t_type AND t_status='Pending'
");
    
$stmt->execute([
    'uid' => $uid,
    'loc_id' => $loc_id,
    'ord_no' => $ord_no, 't_type' => $t_type
]);
//echo json_encode($stmt->fetchAll(PDO::FETCH_ASSOC));
echo json_encode([
    "status" => "success",
    "affected_rows" => $stmt->rowCount()
]);

    try {

        $pdo->beginTransaction();

        // Create sales revenue journal entries from O copy
        $stmt2 = $pdo->prepare("
            INSERT INTO transactions (
                t_date,
                co_id,
                t_tt_doc,
                t_doc_no,
                t_copy,
                t_type,
                t_ct_det,
                t_cr,
                t_item,
                t_qty,
                t_status,
                t_sub_date,
                t_credit,
                t_debit,
                t_entry_by,
                t_conf_by,
                t_narration
            )
            SELECT
                d.t_date,
                d.co_id,
                d.t_tt_doc,
                d.t_doc_no,
                d.t_copy,
                'ledger',
                d.t_ct_det,
                l.ledger_account,
                d.t_item,
                d.t_qty,
                d.t_status,
                d.t_sub_date,
                ROUND((d.t_credit-d.t_sale_vat)-((d.t_credit-d.t_sale_vat)/(100+t.rate)*t.rate),
                        2
                    ),
                ROUND((d.t_debit-d.t_sale_vat)-((d.t_debit-d.t_sale_vat)/(100+t.rate)*t.rate),
                        2
                    ),
                d.t_entry_by,
                d.t_conf_by,
                d.t_type
            FROM transactions d
            LEFT JOIN ledger_map l ON l.co_id = d.co_id 
            LEFT JOIN accounts a ON a.id=l.ledger_account
            LEFT JOIN taxation t ON t.co_id=a.co_id
            WHERE a.PnL='revenue'
              AND d.co_id = ?
              AND d.t_doc_no = ?
              AND d.t_type = ?
              AND d.t_status = 'Confirmed'
              AND d.t_copy = 'O'
              AND NOT EXISTS (
        SELECT 1
        FROM transactions x
        WHERE a.PnL='revenue'
          AND x.co_id = d.co_id
          AND x.t_doc_no = d.t_doc_no
          AND x.t_type = 'ledger'
          AND x.t_item = d.t_item
          AND x.t_cr = l.ledger_account
          AND x.t_narration = d.t_type
                            )
        ");

        $stmt2->execute([$loc_id, $ord_no, $t_type]);
        
    // Create sales tax journal entries from O copy
        $sales_tax = $pdo->prepare("
            INSERT INTO transactions (
                t_date,
                co_id,
                t_tt_doc,
                t_doc_no,
                t_copy,
                t_type,
                t_ct_det,
                t_cr,
                t_item,
                t_qty,
                t_status,
                t_sub_date,
                t_credit,
                t_debit,
                t_entry_by,
                t_conf_by,
                t_narration
            )
            SELECT
                d.t_date,
                d.co_id,
                d.t_tt_doc,
                d.t_doc_no,
                d.t_copy,
                'ledger',
                d.t_ct_det,
                l.ledger_account,
                d.t_item,
                d.t_qty,
                d.t_status,
                d.t_sub_date,
                ROUND(((d.t_credit-d.t_sale_vat)/(100+t.rate)*t.rate),
                        2
                    ),
                ROUND(((d.t_debit-d.t_sale_vat)/(100+t.rate)*t.rate),
                        2
                    ),
                d.t_entry_by,
                d.t_conf_by,
                d.t_type
            FROM transactions d
            LEFT JOIN ledger_map l ON l.co_id = d.co_id 
            LEFT JOIN accounts a ON a.id=l.ledger_account
            LEFT JOIN taxation t ON t.co_id=a.co_id
            WHERE a.PnL='sales_tax'
              AND d.co_id = ?
              AND d.t_doc_no = ?
              AND d.t_type = ?
              AND d.t_status = 'Confirmed'
              AND d.t_copy = 'O'
              AND NOT EXISTS (
        SELECT 1
        FROM transactions x
        WHERE a.PnL='sales_tax'
          AND x.co_id = d.co_id
          AND x.t_doc_no = d.t_doc_no
          AND x.t_type = 'ledger'
          AND x.t_item = d.t_item
          AND x.t_cr = l.ledger_account
          AND x.t_narration = d.t_type
                            )
        ");

        $sales_tax->execute([$loc_id, $ord_no, $t_type]);
        
        
    // Create C.O.G.S  journal entries from O copy
        $stmt_cogs_DEL = $pdo->prepare("
            INSERT INTO transactions (
                t_date,
                co_id,
                t_tt_doc,
                t_doc_no,
                t_copy,
                t_type,
                t_ct_det,
                t_cr,
                t_item,
                t_qty,
                t_status,
                t_sub_date,
                t_credit,
                t_debit,
                t_entry_by,
                t_conf_by,
                t_narration
            )
            SELECT
                d.t_date,
                d.co_id,
                d.t_tt_doc,
                d.t_doc_no,
                d.t_copy,
                'ledger',
                d.t_ct_det,
                l.ledger_account,
                d.t_item,
                d.t_qty,
                d.t_status,
                d.t_sub_date,
                ROUND((d.t_prch_px - d.t_sale_vat) -
                ((d.t_prch_px - d.t_sale_vat) / (100 + t.rate) * t.rate),
                        2
                    ) AS debit,
                '' AS credit,
                d.t_entry_by,
                d.t_conf_by,
                d.t_type
            FROM transactions d
            LEFT JOIN ledger_map l ON l.co_id = d.co_id
            LEFT JOIN accounts a ON a.id = l.ledger_account
            LEFT JOIN taxation t ON t.co_id = a.co_id
            WHERE a.PnL = 'cost'
              AND d.co_id = ?
              AND d.t_doc_no = ?
              AND d.t_type = ?
              AND d.t_status = 'Confirmed'
              AND d.t_copy = 'O'
              AND d.t_type = 'DEL'
              AND NOT EXISTS (
        SELECT 1
        FROM transactions x
        WHERE a.PnL='cost'
          AND x.co_id = d.co_id
          AND x.t_doc_no = d.t_doc_no
          AND x.t_type = 'ledger'
          AND x.t_item = d.t_item
          AND x.t_cr = l.ledger_account
          AND x.t_narration = d.t_type
                            )
            
           
            
        ");
        
        $stmt_cogs_GR = $pdo->prepare("
            INSERT INTO transactions (
                t_date,
                co_id,
                t_tt_doc,
                t_doc_no,
                t_copy,
                t_type,
                t_ct_det,
                t_cr,
                t_item,
                t_qty,
                t_status,
                t_sub_date,
                t_credit,
                t_debit,
                t_entry_by,
                t_conf_by,
                t_narration
            )
           
            SELECT
                d.t_date,
                d.co_id,
                d.t_tt_doc,
                d.t_doc_no,
                d.t_copy,
                'ledger',
                d.t_ct_det,
                l.ledger_account,
                d.t_item,
                d.t_qty,
                d.t_status,
                d.t_sub_date,
                '' AS debit,
                ROUND((d.t_prch_px - d.t_sale_vat) -
                ((d.t_prch_px - d.t_sale_vat) / (100 + t.rate) * t.rate),
                        2
                    ) AS credit,
                d.t_entry_by,
                d.t_conf_by,
                d.t_type
            FROM transactions d
            LEFT JOIN ledger_map l ON l.co_id = d.co_id
            LEFT JOIN accounts a ON a.id = l.ledger_account
            LEFT JOIN taxation t ON t.co_id = a.co_id
            WHERE a.PnL = 'cost'
              AND d.co_id = ?
              AND d.t_doc_no = ?
              AND d.t_type = ?
              AND d.t_status = 'Confirmed'
              AND d.t_copy = 'O'
              AND d.t_type = 'GR'
              AND NOT EXISTS (
        SELECT 1
        FROM transactions x
        WHERE a.PnL='cost'
          AND x.co_id = d.co_id
          AND x.t_doc_no = d.t_doc_no
          AND x.t_type = 'ledger'
          AND x.t_item = d.t_item
          AND x.t_cr = l.ledger_account
          AND x.t_narration = d.t_type
                            )
            
        ");
        
        if ($t_type === 'DEL' ) {
        $stmt_cogs_DEL->execute([$loc_id, $ord_no, $t_type]);
        }
         if ( $t_type === 'GR') {
            $stmt_cogs_GR->execute([$loc_id, $ord_no, $t_type]);
        }
    
        $pdo->commit();

        //echo json_encode(["status" => "success"]);

    } catch (PDOException $e) {

        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }

        error_log("Delivery Confirmation Error: " . $e->getMessage());

        echo json_encode([
            'status' => 'error',
            'message' => 'Failed to confirm Delivery transaction'
        ]);
    }
}
        

if ($t_type==='REC' || $t_type==='EXP') {

$stmt = $pdo->prepare("
    UPDATE transactions SET t_status='Confirmed', t_conf_by= :uid, t_conf_date=Now() WHERE co_id= :loc_id AND t_doc_no= :ord_no AND t_type= :t_type AND t_status='Pending'
");
    
$stmt->execute([
    'uid' => $uid,
    'loc_id' => $loc_id,
    'ord_no' => $ord_no, 't_type' => $t_type
]);

//echo json_encode($stmt->fetchAll(PDO::FETCH_ASSOC));
echo json_encode([
    "status" => "success",
    "affected_rows" => $stmt->rowCount()
]);

    try {

        $pdo->beginTransaction();
        
    // Create discount deduction tax journal entries from O copy
    
        $rec_disc_tax = $pdo->prepare("
            INSERT INTO transactions (
                t_date,
                co_id,
                t_tt_doc,
                t_doc_no,
                t_copy,
                t_type,
                t_ct_det,
                t_cr,
                t_item,
                t_qty,
                t_status,
                t_sub_date,
                t_debit,
                t_entry_by,
                t_conf_by,
                t_narration
            )
            SELECT
                d.t_date,
                d.co_id,
                d.t_tt_doc,
                d.t_doc_no,
                d.t_copy,
                'ledger',
                d.t_ct_det,
                l.ledger_account,
                d.t_item,
                d.t_qty,
                d.t_status,
                d.t_sub_date,
                 ROUND((d.t_credit/(100+t.rate)*t.rate),
                        2
                    ),
                d.t_entry_by,
                d.t_conf_by,
                d.t_type
            FROM transactions d
            LEFT JOIN ledger_map l ON l.co_id = d.co_id 
            LEFT JOIN accounts a ON a.id=l.ledger_account
            LEFT JOIN taxation t ON t.co_id=a.co_id
            LEFT JOIN accounts b ON d.t_cr=b.id
            WHERE a.PnL='sales_tax'
             AND b.acc_type='Discount'
              AND d.co_id = ?
              AND d.t_doc_no = ?
              AND d.t_type = ?
              AND d.t_status = 'Confirmed'
              AND d.t_copy = 'O'
              AND NOT EXISTS (
        SELECT 1
        FROM transactions x
        WHERE a.PnL='sales_tax'
          AND x.co_id = d.co_id
          AND x.t_doc_no = d.t_doc_no
          AND x.t_type = 'ledger'
          AND x.t_item = d.t_item
          AND x.t_cr = l.ledger_account
          AND x.t_narration = d.t_type
                            )
        ");

        $rec_disc_tax->execute([$loc_id, $ord_no, $t_type]);

        $pdo->commit();

        //echo json_encode(["status" => "success"]);

    } catch (PDOException $e) {

        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }

        error_log("Delivery Confirmation Error: " . $e->getMessage());

        echo json_encode([
            'status' => 'error',
            'message' => 'Failed to confirm Delivery transaction'
        ]);
    }
    
}

if ($t_type === 'LO') {

    try {

        $pdo->beginTransaction();

        // Create PRCH entries from O copy
        $stmt2 = $pdo->prepare("
            INSERT INTO transactions (
                t_date,
                co_id,
                t_tt_doc,
                t_doc_no,
                t_copy,
                t_type,
                t_ct_det,
                t_cr,
                t_item,
                t_qty,
                t_status,
                t_sub_date,
                t_entry_by
            )
            SELECT
                t_date,
                co_id,
                t_tt_doc,
                t_doc_no,
                t_copy,
                'PRCH',
                t_ct_det,
                t_ct_det,
                t_item,
                t_qty,
                t_status,
                t_sub_date,
                t_entry_by
            FROM transactions
            WHERE co_id = ?
              AND t_doc_no = ?
              AND t_type = ?
              AND t_status = 'Pending'
              AND t_copy = 'O'
        ");

        $stmt2->execute([$loc_id, $ord_no, $t_type]);

        // Create PRCH entries from D copy
        $stmt3 = $pdo->prepare("
            INSERT INTO transactions (
                t_date,
                co_id,
                t_tt_doc,
                t_doc_no,
                t_copy,
                t_type,
                t_ct_det,
                t_cr,
                t_item,
                t_qty,
                t_debit,
                t_status,
                t_sub_date,
                t_entry_by
            )
            SELECT
                t_date,
                co_id,
                t_tt_doc,
                t_doc_no,
                'D',
                'PRCH',
                t_ct_det,
                t_cr,
                t_item,
                t_qty,
                t_credit,
                t_status,
                t_sub_date,
                t_entry_by
            FROM transactions
            WHERE co_id = ?
              AND t_doc_no = ?
              AND t_type = ?
              AND t_status = 'Pending'
              AND t_copy = 'O'
        ");

        $stmt3->execute([$loc_id, $ord_no, $t_type]);
        
    // Update source transactions (O copy)
        $stmt2_update = $pdo->prepare("
            UPDATE transactions t
            JOIN products p ON p.id = t.t_item
            SET
                t.t_credit    = t.t_qty * p.p_sale_px,
            
                t.t_prch_px   = t.t_qty * p.p_prch_px,
                t.t_prch_vat  = t.t_qty * p.inp_vat,
                t.t_sku       = t.t_qty * p.sku,
                t.admin_fee   = t.t_qty * p.admin_fee
            WHERE t.co_id = ?
              AND t.t_doc_no = ?
              AND t.t_type = 'PRCH'
              AND t.t_status = 'Pending'
              AND t.t_copy = 'O'
        ");

        $stmt2_update->execute([$loc_id, $ord_no]);

      // Update destination transactions (D copy)
        $stmt3_update = $pdo->prepare("
            UPDATE transactions t
            JOIN products p ON p.id = t.t_item
            SET
                t.t_debit = t.t_qty * p.p_sale_px
            WHERE t.co_id = ?
              AND t.t_doc_no = ?
              AND t.t_type = 'PRCH'
              AND t.t_status = 'Pending'
              AND t.t_copy = 'D'
        ");

      //  $stmt3_update->execute([$loc_id, $ord_no]);

        // Confirm original LO transactions
        $stmtConfirm = $pdo->prepare("
            UPDATE transactions
            SET
                t_status = 'Confirmed',
                t_conf_by = :uid,
                t_conf_date = NOW()
            WHERE co_id = :loc_id
              AND t_doc_no = :ord_no
              AND t_type = :t_type
              AND t_status = 'Pending'
        ");

        $stmtConfirm->execute([
            'uid'    => $uid,
            'loc_id' => $loc_id,
            'ord_no' => $ord_no,
            't_type' => $t_type
        ]);

        $pdo->commit();

        echo json_encode([
            'status' => 'success',
            'message' => 'LO transaction confirmed successfully'
        ]);

    } catch (PDOException $e) {

        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }

        error_log("LO Confirmation Error: " . $e->getMessage());

        echo json_encode([
            'status' => 'error',
            'message' => 'Failed to confirm LO transaction'
        ]);
    }
}




?>

