File size: 21,252 Bytes
edcf070
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d3525b4
 
 
 
 
 
 
 
 
 
edcf070
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6fd3b19
edcf070
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
package controllers

import (
	"encoding/json"
	"fmt"
	"io"
	"log"
	"math/rand"
	"net/http"
	"strconv"
	"time"

	"service-warungpos-go/config"
	"service-warungpos-go/models"
	"service-warungpos-go/services"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

// DTOs untuk Order & Payment
type OrderItemCreate struct {
	ProductID uint `json:"product_id" binding:"required"`
	Quantity  int  `json:"quantity" binding:"required,gt=0"`
}

type OrderCreateRequest struct {
	BranchID *uint             `json:"branch_id"`
	Items    []OrderItemCreate `json:"items" binding:"required,dive"`
}

type OrderItemResponse struct {
	ID          uint   `json:"id"`
	ProductID   uint   `json:"product_id"`
	ProductName string `json:"product_name"`
	Quantity    int    `json:"quantity"`
	UnitPrice   int    `json:"unit_price"`
	Subtotal    int    `json:"subtotal"`
}

type OrderResponse struct {
	ID              uint                `json:"id"`
	OrderNumber     string              `json:"order_number"`
	BranchID        *uint               `json:"branch_id"`
	BranchName      string              `json:"branch_name"`
	TotalAmount     int                 `json:"total_amount"`
	PaidAmount      int                 `json:"paid_amount"`
	ChangeAmount    int                 `json:"change_amount"`
	PaymentMethod   string              `json:"payment_method"`
	PaymentStatus   string              `json:"payment_status"`
	MidtransOrderID string              `json:"midtrans_order_id"`
	MidtransToken   string              `json:"midtrans_token"`
	Items           []OrderItemResponse `json:"items"`
	CreatedAt       time.Time           `json:"created_at"`
}

type CashPaymentRequest struct {
	OrderID       uint   `json:"order_id" binding:"required"`
	PaidAmount    int    `json:"paid_amount" binding:"required,gt=0"`
	CustomerName  string `json:"customer_name"`
	CustomerPhone string `json:"customer_phone"`
}

type MidtransPaymentRequest struct {
	OrderID       uint   `json:"order_id" binding:"required"`
	CustomerName  string `json:"customer_name"`
	CustomerEmail string `json:"customer_email"`
	CustomerPhone string `json:"customer_phone"`
}

type PaymentStatusResponse struct {
	OrderID       uint   `json:"order_id"`
	OrderNumber   string `json:"order_number"`
	PaymentStatus string `json:"payment_status"`
	PaymentMethod string `json:"payment_method"`
	TotalAmount   int    `json:"total_amount"`
	PaidAmount    int    `json:"paid_amount"`
	ChangeAmount  int    `json:"change_amount"`
}

func generateOrderNumber() string {
	now := time.Now()
	dateStr := now.Format("20060102")
	// Hex unik dari random number
	uniqueVal := rand.Intn(65536)
	return fmt.Sprintf("WP-%s-%04X", dateStr, uniqueVal)
}

func toOrderResponse(order *models.Order) OrderResponse {
	var itemsResp []OrderItemResponse
	for _, item := range order.Items {
		pName := "Produk Terhapus"
		if item.Product != nil {
			pName = item.Product.Name
		}
		itemsResp = append(itemsResp, OrderItemResponse{
			ID:          item.ID,
			ProductID:   item.ProductID,
			ProductName: pName,
			Quantity:    item.Quantity,
			UnitPrice:   item.UnitPrice,
			Subtotal:    item.Subtotal,
		})
	}

	bName := ""
	if order.Branch != nil {
		bName = order.Branch.Name
	}

	return OrderResponse{
		ID:              order.ID,
		OrderNumber:     order.OrderNumber,
		BranchID:        order.BranchID,
		BranchName:      bName,
		TotalAmount:     order.TotalAmount,
		PaidAmount:      order.PaidAmount,
		ChangeAmount:    order.ChangeAmount,
		PaymentMethod:   order.PaymentMethod,
		PaymentStatus:   order.PaymentStatus,
		MidtransOrderID: order.MidtransOrderID,
		MidtransToken:   order.MidtransToken,
		Items:           itemsResp,
		CreatedAt:       order.CreatedAt,
	}
}

// ==================== ORDER CONTROLLER ====================

func CreateOrder(c *gin.Context) {
	userVal, _ := c.Get("user")
	user := userVal.(*models.User)

	var req OrderCreateRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"detail": err.Error()})
		return
	}

	// Tentukan branch_id yang berlaku
	var effectiveBranchID *uint
	if user.Role == "owner" {
		effectiveBranchID = req.BranchID
	} else {
		effectiveBranchID = user.BranchID
	}

	orderNumber := generateOrderNumber()

	tx := config.DB.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()

	order := models.Order{
		CompanyID:     *user.CompanyID,
		BranchID:      effectiveBranchID,
		OrderNumber:   orderNumber,
		TotalAmount:   0,
		PaymentStatus: "pending",
	}

	if err := tx.Create(&order).Error; err != nil {
		tx.Rollback()
		c.JSON(http.StatusInternalServerError, gin.H{"detail": "Gagal menyimpan order"})
		return
	}

	total := 0
	for _, item := range req.Items {
		var product models.Product
		if err := tx.Where("id = ? AND company_id = ?", item.ProductID, *user.CompanyID).First(&product).Error; err != nil {
			tx.Rollback()
			c.JSON(http.StatusBadRequest, gin.H{"detail": fmt.Sprintf("Produk dengan ID %d tidak ditemukan", item.ProductID)})
			return
		}

		if !product.IsActive {
			tx.Rollback()
			c.JSON(http.StatusBadRequest, gin.H{"detail": fmt.Sprintf("Produk '%s' sudah tidak aktif", product.Name)})
			return
		}

		// Periksa dan kurangi stok jika stok terbatas (bukan unlimited)
		if !product.IsUnlimitedStock {
			if product.Stock < item.Quantity {
				tx.Rollback()
				c.JSON(http.StatusBadRequest, gin.H{"detail": fmt.Sprintf("Stok '%s' tidak cukup (sisa: %d)", product.Name, product.Stock)})
				return
			}
			product.Stock -= item.Quantity
			if err := tx.Save(&product).Error; err != nil {
				tx.Rollback()
				c.JSON(http.StatusInternalServerError, gin.H{"detail": "Gagal memperbarui stok produk"})
				return
			}
		}

		subtotal := product.Price * item.Quantity
		orderItem := models.OrderItem{
			OrderID:   order.ID,
			ProductID: product.ID,
			Quantity:  item.Quantity,
			UnitPrice: product.Price,
			Subtotal:  subtotal,
		}
		if err := tx.Create(&orderItem).Error; err != nil {
			tx.Rollback()
			c.JSON(http.StatusInternalServerError, gin.H{"detail": "Gagal menyimpan item order"})
			return
		}

		total += subtotal
	}

	// Update total amount order
	order.TotalAmount = total
	if err := tx.Save(&order).Error; err != nil {
		tx.Rollback()
		c.JSON(http.StatusInternalServerError, gin.H{"detail": "Gagal meng-update total transaksi"})
		return
	}

	if err := tx.Commit().Error; err != nil {
		tx.Rollback()
		c.JSON(http.StatusInternalServerError, gin.H{"detail": "Gagal memproses transaksi"})
		return
	}

	// Load relationships untuk response
	config.DB.Preload("Branch").Preload("Items.Product").First(&order, order.ID)

	c.JSON(http.StatusCreated, toOrderResponse(&order))
}

func ListOrders(c *gin.Context) {
	userVal, _ := c.Get("user")
	user := userVal.(*models.User)

	skipStr := c.DefaultQuery("skip", "0")
	limitStr := c.DefaultQuery("limit", "50")
	dateFrom := c.Query("date_from") // YYYY-MM-DD
	dateTo := c.Query("date_to")     // YYYY-MM-DD
	branchFilter := c.Query("branch_id")

	skip, _ := strconv.Atoi(skipStr)
	limit, _ := strconv.Atoi(limitStr)

	query := config.DB.Select("id, company_id, branch_id, order_number, total_amount, paid_amount, change_amount, payment_method, payment_status, midtrans_order_id, midtrans_token, created_at").
		Preload("Branch", func(db *gorm.DB) *gorm.DB {
			return db.Select("id, name")
		}).
		Preload("Items", func(db *gorm.DB) *gorm.DB {
			return db.Select("id, order_id, product_id, quantity, unit_price, subtotal")
		}).
		Preload("Items.Product", func(db *gorm.DB) *gorm.DB {
			return db.Select("id, name")
		}).
		Where("company_id = ?", *user.CompanyID).
		Order("created_at desc")

	if dateFrom != "" {
		dtFrom, err := time.Parse("2006-01-02", dateFrom)
		if err == nil {
			// Awal hari (00:00:00)
			query = query.Where("created_at >= ?", dtFrom)
		}
	}

	if dateTo != "" {
		dtTo, err := time.Parse("2006-01-02", dateTo)
		if err == nil {
			// Akhir hari (23:59:59)
			dtToEnd := dtTo.Add(23*time.Hour + 59*time.Minute + 59*time.Second)
			query = query.Where("created_at <= ?", dtToEnd)
		}
	}

	if branchFilter != "" {
		if bID, err := strconv.Atoi(branchFilter); err == nil {
			query = query.Where("branch_id = ?", bID)
		}
	}

	var orders []models.Order
	if err := query.Offset(skip).Limit(limit).Find(&orders).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"detail": "Gagal mengambil histori order"})
		return
	}

	var resp []OrderResponse
	for _, o := range orders {
		resp = append(resp, toOrderResponse(&o))
	}

	c.JSON(http.StatusOK, resp)
}

func GetOrder(c *gin.Context) {
	userVal, _ := c.Get("user")
	user := userVal.(*models.User)

	orderIDStr := c.Param("order_id")
	orderID, err := strconv.Atoi(orderIDStr)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"detail": "ID order tidak valid"})
		return
	}

	var order models.Order
	if err := config.DB.Preload("Branch").Preload("Items.Product").Where("id = ? AND company_id = ?", orderID, *user.CompanyID).First(&order).Error; err != nil {
		c.JSON(http.StatusNotFound, gin.H{"detail": "Order tidak ditemukan"})
		return
	}

	c.JSON(http.StatusOK, toOrderResponse(&order))
}

// ==================== PAYMENT CONTROLLER ====================

func PayCash(c *gin.Context) {
	userVal, _ := c.Get("user")
	user := userVal.(*models.User)

	var req CashPaymentRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"detail": err.Error()})
		return
	}

	tx := config.DB.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()

	var order models.Order
	if err := tx.Preload("Items.Product").Where("id = ? AND company_id = ?", req.OrderID, *user.CompanyID).First(&order).Error; err != nil {
		tx.Rollback()
		c.JSON(http.StatusNotFound, gin.H{"detail": "Order tidak ditemukan"})
		return
	}

	if order.PaymentStatus == "paid" {
		tx.Rollback()
		c.JSON(http.StatusBadRequest, gin.H{"detail": "Order sudah dibayar"})
		return
	}

	if req.PaidAmount < order.TotalAmount {
		tx.Rollback()
		c.JSON(http.StatusBadRequest, gin.H{
			"detail": fmt.Sprintf("Uang kurang! Total: %s, Dibayar: %s, Kurang: %s",
				fmtRupiah(order.TotalAmount),
				fmtRupiah(req.PaidAmount),
				fmtRupiah(order.TotalAmount-req.PaidAmount),
			),
		})
		return
	}

	// Update order data
	order.PaymentMethod = "cash"
	order.PaymentStatus = "paid"
	order.PaidAmount = req.PaidAmount
	order.ChangeAmount = req.PaidAmount - order.TotalAmount

	// Hitung fee platform berdasarkan Company
	var company models.Company
	if err := tx.First(&company, *user.CompanyID).Error; err == nil {
		order.PlatformFee = int(float64(order.TotalAmount) * company.FeePercentage / 100)
	}

	if err := tx.Save(&order).Error; err != nil {
		tx.Rollback()
		c.JSON(http.StatusInternalServerError, gin.H{"detail": "Gagal menyelesaikan pembayaran"})
		return
	}

	if err := tx.Commit().Error; err != nil {
		tx.Rollback()
		c.JSON(http.StatusInternalServerError, gin.H{"detail": "Gagal memproses pembayaran"})
		return
	}

	// Kirim Notifikasi WA (Async)
	if req.CustomerPhone != "" {
		go func() {
			var waItems []services.WAItem
			for _, item := range order.Items {
				pName := "Item"
				if item.Product != nil {
					pName = item.Product.Name
				}
				waItems = append(waItems, services.WAItem{
					Name:     pName,
					Quantity: item.Quantity,
					Price:    item.UnitPrice,
				})
			}

			var branchName string
			if order.BranchID != nil {
				var branch models.Branch
				if err := config.DB.First(&branch, *order.BranchID).Error; err == nil {
					branchName = branch.Name
				}
			}

			services.SendPaymentNotification(
				req.CustomerPhone,
				order.OrderNumber,
				order.TotalAmount,
				"cash",
				req.CustomerName,
				waItems,
				order.ChangeAmount,
				company.Name,
				branchName,
			)
		}()
	}

	c.JSON(http.StatusOK, PaymentStatusResponse{
		OrderID:       order.ID,
		OrderNumber:   order.OrderNumber,
		PaymentStatus: order.PaymentStatus,
		PaymentMethod: order.PaymentMethod,
		TotalAmount:   order.TotalAmount,
		PaidAmount:    order.PaidAmount,
		ChangeAmount:  order.ChangeAmount,
	})
}

func PayTripay(c *gin.Context) {
	userVal, _ := c.Get("user")
	user := userVal.(*models.User)

	var req MidtransPaymentRequest // Gunakan request DTO yang sama karena field input sama
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"detail": err.Error()})
		return
	}

	var order models.Order
	if err := config.DB.Where("id = ? AND company_id = ?", req.OrderID, *user.CompanyID).First(&order).Error; err != nil {
		c.JSON(http.StatusNotFound, gin.H{"detail": "Order tidak ditemukan"})
		return
	}

	if order.PaymentStatus == "paid" {
		c.JSON(http.StatusBadRequest, gin.H{"detail": "Order sudah dibayar"})
		return
	}

	// Load order items untuk dikirim ke Tripay
	var orderItems []models.OrderItem
	config.DB.Preload("Product").Where("order_id = ?", order.ID).Find(&orderItems)

	var tripayItems []services.TripayItem
	for _, item := range orderItems {
		skuStr := ""
		if item.Product != nil && item.Product.SKU != nil {
			skuStr = *item.Product.SKU
		}
		pName := "Product"
		if item.Product != nil {
			pName = item.Product.Name
		}
		tripayItems = append(tripayItems, services.TripayItem{
			SKU:      skuStr,
			Name:     pName,
			Price:    item.UnitPrice,
			Quantity: item.Quantity,
		})
	}

	// Request Tripay Transaction (Default ke QRIS yang paling populer)
	tripayRes, err := services.CreateTripayTransaction(
		order.OrderNumber,
		order.TotalAmount,
		"QRIS",
		req.CustomerName,
		req.CustomerEmail,
		req.CustomerPhone,
		tripayItems,
		order.CompanyID,
	)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"detail": fmt.Sprintf("Gagal membuat transaksi Tripay: %v", err)})
		return
	}

	// Simpan Tripay details ke DB
	order.MidtransOrderID = tripayRes.Data.Reference // Simpan nomor referensi Tripay di midtrans_order_id demi kecocokan DB
	order.MidtransToken = tripayRes.Data.CheckoutURL // Simpan checkout_url di midtrans_token demi kecocokan DB
	order.PaymentMethod = "tripay"
	config.DB.Save(&order)

	// Kembalikan JSON yang kompatibel dengan format respons frontend agar tidak merusak UI kasir
	c.JSON(http.StatusOK, gin.H{
		"order_id":     order.ID,
		"order_number": order.OrderNumber,
		"snap_token":   tripayRes.Data.Reference,
		"redirect_url": tripayRes.Data.CheckoutURL,
		"total_amount": order.TotalAmount,
	})
}

func TripayWebhook(c *gin.Context) {
	// Baca raw body untuk verifikasi signature
	rawBody, err := io.ReadAll(c.Request.Body)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"detail": "Gagal membaca request body"})
		return
	}

	// Parse JSON manual
	var notification map[string]interface{}
	if err := json.Unmarshal(rawBody, &notification); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"detail": "Request body harus berupa JSON yang valid"})
		return
	}

	// Validasi header signature
	signature := c.GetHeader("X-Callback-Signature")
	if signature == "" {
		c.JSON(http.StatusBadRequest, gin.H{"detail": "Header X-Callback-Signature tidak ditemukan"})
		return
	}

	log.Printf("[WEBHOOK] Tripay payload: %s", string(rawBody))

	// Verifikasi Signature keaslian Tripay
	if !services.VerifyTripaySignature(rawBody, signature) {
		c.JSON(http.StatusUnauthorized, gin.H{"detail": "Signature verifikasi gagal/tidak valid"})
		return
	}

	merchantRefVal, ok := notification["merchant_ref"]
	if !ok || merchantRefVal == nil {
		c.JSON(http.StatusBadRequest, gin.H{"detail": "Payload webhook tidak valid: merchant_ref wajib ada"})
		return
	}

	merchantRefStr := merchantRefVal.(string)
	tripayStatus, _ := notification["status"].(string)

	log.Printf("[WEBHOOK] Tripay: merchant_ref=%s, status=%s", merchantRefStr, tripayStatus)

	tx := config.DB.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()

	var order models.Order
	if err := tx.Preload("Items.Product").Where("order_number = ?", merchantRefStr).First(&order).Error; err != nil {
		tx.Rollback()
		c.JSON(http.StatusNotFound, gin.H{"detail": "Order tidak ditemukan"})
		return
	}

	oldStatus := order.PaymentStatus

	// Map status Tripay: PAID, EXPIRED, FAILED
	switch tripayStatus {
	case "PAID":
		order.PaymentStatus = "paid"
		order.PaidAmount = order.TotalAmount
	case "EXPIRED", "FAILED":
		order.PaymentStatus = "failed"
		if oldStatus != "failed" {
			restoreStock(tx, &order)
		}
	}

	// Jika sukses terbayar, hitung platform fee
	if order.PaymentStatus == "paid" && oldStatus != "paid" {
		var company models.Company
		if err := tx.First(&company, order.CompanyID).Error; err == nil {
			order.PlatformFee = int(float64(order.TotalAmount) * company.FeePercentage / 100)
		}
	}

	if err := tx.Save(&order).Error; err != nil {
		tx.Rollback()
		c.JSON(http.StatusInternalServerError, gin.H{"detail": "Gagal memproses status webhook"})
		return
	}

	if err := tx.Commit().Error; err != nil {
		tx.Rollback()
		c.JSON(http.StatusInternalServerError, gin.H{"detail": "Gagal menyelesaikan commit webhook"})
		return
	}

	log.Printf("[WEBHOOK] Order %s di-update via Tripay: %s -> %s", order.OrderNumber, oldStatus, order.PaymentStatus)

	// Kirim Notifikasi WA struk belanja jika pembayaran berhasil
	if order.PaymentStatus == "paid" && oldStatus != "paid" {
		go func() {
			custPhone, _ := notification["customer_phone"].(string)
			custName, _ := notification["customer_name"].(string)
			if custName == "" {
				custName = "Customer"
			}

			var waItems []services.WAItem
			for _, item := range order.Items {
				pName := "Item"
				if item.Product != nil {
					pName = item.Product.Name
				}
				waItems = append(waItems, services.WAItem{
					Name:     pName,
					Quantity: item.Quantity,
					Price:    item.UnitPrice,
				})
			}

			var company models.Company
			config.DB.First(&company, order.CompanyID)

			var branchName string
			if order.BranchID != nil {
				var branch models.Branch
				if err := config.DB.First(&branch, *order.BranchID).Error; err == nil {
					branchName = branch.Name
				}
			}

			if custPhone != "" {
				services.SendPaymentNotification(
					custPhone,
					order.OrderNumber,
					order.TotalAmount,
					"tripay",
					custName,
					waItems,
					0,
					company.Name,
					branchName,
				)
			}
		}()
	}

	c.JSON(http.StatusOK, gin.H{
		"success":      true,
		"order_number": order.OrderNumber,
	})
}

func GetPaymentStatus(c *gin.Context) {
	userVal, _ := c.Get("user")
	user := userVal.(*models.User)

	orderIDStr := c.Param("order_id")
	orderID, err := strconv.Atoi(orderIDStr)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"detail": "ID order tidak valid"})
		return
	}

	var order models.Order
	if err := config.DB.Where("id = ? AND company_id = ?", orderID, *user.CompanyID).First(&order).Error; err != nil {
		c.JSON(http.StatusNotFound, gin.H{"detail": "Order tidak ditemukan"})
		return
	}

	c.JSON(http.StatusOK, PaymentStatusResponse{
		OrderID:       order.ID,
		OrderNumber:   order.OrderNumber,
		PaymentStatus: order.PaymentStatus,
		PaymentMethod: order.PaymentMethod,
		TotalAmount:   order.TotalAmount,
		PaidAmount:    order.PaidAmount,
		ChangeAmount:  order.ChangeAmount,
	})
}

func CancelMidtransOrder(c *gin.Context) {
	userVal, _ := c.Get("user")
	user := userVal.(*models.User)

	orderIDStr := c.Param("order_id")
	orderID, err := strconv.Atoi(orderIDStr)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"detail": "ID order tidak valid"})
		return
	}

	tx := config.DB.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()

	var order models.Order
	if err := tx.Preload("Items.Product").Where("id = ? AND company_id = ?", orderID, *user.CompanyID).First(&order).Error; err != nil {
		tx.Rollback()
		c.JSON(http.StatusNotFound, gin.H{"detail": "Order tidak ditemukan"})
		return
	}

	if order.PaymentStatus == "paid" {
		tx.Rollback()
		c.JSON(http.StatusBadRequest, gin.H{"detail": "Order sudah dibayar"})
		return
	}

	if order.PaymentStatus == "cancelled" {
		tx.Rollback()
		c.JSON(http.StatusOK, gin.H{
			"status":         "cancelled",
			"order_id":       order.ID,
			"order_number":   order.OrderNumber,
			"payment_status": order.PaymentStatus,
		})
		return
	}

	oldStatus := order.PaymentStatus
	order.PaymentStatus = "cancelled"

	if oldStatus != "cancelled" {
		restoreStock(tx, &order)
	}

	if err := tx.Save(&order).Error; err != nil {
		tx.Rollback()
		c.JSON(http.StatusInternalServerError, gin.H{"detail": "Gagal membatalkan order"})
		return
	}

	if err := tx.Commit().Error; err != nil {
		tx.Rollback()
		c.JSON(http.StatusInternalServerError, gin.H{"detail": "Gagal menyelesaikan proses pembatalan"})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"status":         "cancelled",
		"order_id":       order.ID,
		"order_number":   order.OrderNumber,
		"payment_status": order.PaymentStatus,
	})
}

// Helpers
func restoreStock(tx *gorm.DB, order *models.Order) {
	// GORM raw query atau update
	for _, item := range order.Items {
		var product models.Product
		if err := tx.First(&product, item.ProductID).Error; err == nil {
			if !product.IsUnlimitedStock {
				product.Stock += item.Quantity
				tx.Save(&product)
				log.Printf("[RESTORE] Stok '%s' dikembalikan +%d (sekarang: %d)", product.Name, item.Quantity, product.Stock)
			}
		}
	}
}