File size: 6,830 Bytes
841722b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using QuickInvoiceSaaS.Data;
using QuickInvoiceSaaS.Models;

namespace QuickInvoiceSaaS.Controllers
{
    [Authorize] // 🔥 حماية الـ Controller بالكامل (لن يدخل أحد إلا بتسجيل دخول)
    public class InvoicesWebController : Controller
    {
        private readonly ApplicationDbContext _context;
        private readonly UserManager<ApplicationUser> _userManager;

        public InvoicesWebController(ApplicationDbContext context, UserManager<ApplicationUser> userManager)
        {
            _context = context;
            _userManager = userManager;
        }

        // --- 1. عرض فواتير الشركة الخاصة بالمستخدم فقط ---
        public async Task<IActionResult> Index()
        {
            // جلب بيانات المستخدم الحالي المسجل دخوله
            var user = await _userManager.GetUserAsync(User);
            if (user == null) return Challenge();

            var tenantId = user.TenantId;
            ViewData["CurrentTenant"] = tenantId;

            // عزل حقيقي: جلب الفواتير التي تطابق TenantId الخاص بالمستخدم فقط!
            var invoices = await _context.Invoices
                .IgnoreQueryFilters()
                .Where(i => i.TenantId == tenantId)
                .ToListAsync();

            // حساب الإحصائيات للواجهة بناءً على بيانات الشركة الحالية
            ViewData["TotalInvoicesCount"] = invoices.Count;
            ViewData["UniqueClientsCount"] = invoices.Select(i => i.ClientName).Distinct().Count();

            return View(invoices);
        }
        // --- 4. صفحة تعديل الفاتورة (HttpGet) ---
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null) return NotFound();

            // جلب المستخدم الحالي لمعرفة شركته
            var user = await _userManager.GetUserAsync(User);
            if (user == null) return Challenge();

            // جلب الفاتورة بشرط أن تكون تابعة لنفس الـ TenantId لحماية البيانات 🔐
            var invoice = await _context.Invoices
                .IgnoreQueryFilters()
                .FirstOrDefaultAsync(i => i.Id == id && i.TenantId == user.TenantId);

            if (invoice == null) return Forbid(); // منع الوصول إذا كانت الفاتورة لشركة أخرى

            return View(invoice);
        }

        // --- 5. حفظ تعديل الفاتورة (HttpPost) ---
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int id, Invoice invoice)
        {
            if (id != invoice.Id) return NotFound();

            var user = await _userManager.GetUserAsync(User);
            if (user == null) return Challenge();

            // التأكد قبل الحفظ أن الفاتورة الأصلية تابعة للمستخدم الحالي
            var existingInvoice = await _context.Invoices
                .IgnoreQueryFilters()
                .AsNoTracking()
                .FirstOrDefaultAsync(i => i.Id == id && i.TenantId == user.TenantId);

            if (existingInvoice == null) return Forbid();

            if (ModelState.IsValid)
            {
                try
                {
                    invoice.TenantId = user.TenantId; // إعادة حقن الـ TenantId لضمان عدم التلاعب
                    _context.Update(invoice);
                    await _context.SaveChangesAsync();
                    return RedirectToAction(nameof(Index));
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!_context.Invoices.Any(e => e.Id == invoice.Id)) return NotFound();
                    else throw;
                }
            }
            return View(invoice);
        }

        // --- 6. حذف الفاتورة مباشرة (HttpPost لحماية أمنية أفضل) ---
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Delete(int id)
        {
            var user = await _userManager.GetUserAsync(User);
            if (user == null) return Challenge();

            // جلب الفاتورة الخاصة بالشركة فقط لحذفها
            var invoice = await _context.Invoices
                .IgnoreQueryFilters()
                .FirstOrDefaultAsync(i => i.Id == id && i.TenantId == user.TenantId);

            if (invoice == null) return Forbid();

            _context.Invoices.Remove(invoice);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }

        // --- 2. صفحة إنشاء فاتورة جديدة (HttpGet) ---
        public IActionResult Create() => View();

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create(Invoice invoice)
        {
            var user = await _userManager.GetUserAsync(User);
            if (user == null) return Challenge();

            // 🔒 فحص خطة الاشتراك والحد الأقصى للفواتير
            if (user.SubscriptionPlan == "Free")
            {
                // حساب عدد فواتير هذه الشركة حالياً في قاعدة البيانات
                var currentInvoicesCount = await _context.Invoices
                    .IgnoreQueryFilters()
                    .CountAsync(i => i.TenantId == user.TenantId);

                if (currentInvoicesCount >= 3)
                {
                    // إظهار رسالة خطأ تمنع الحفظ وتطلب الترقية
                    ModelState.AddModelError("", "⚠️ لقد استهلكت الحد الأقصى للباقة المجانية (3 فواتير). يرجى الترقية إلى الباقة الممتازة لإضافة المزيد!");
                    return View(invoice);
                }
            }

            invoice.TenantId = user.TenantId;

            try
            {
                _context.Invoices.Add(invoice);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", "حدث خطأ أثناء الحفظ: " + ex.Message);
            }

            return View(invoice);
        }
    }
}